feat(manager): customers, throwaways, stock and notes on v2 (platform-v2 step 6.13b)

- CRM -> Customers: search ignoring case and Greek accents (and part of the phone), visits / spent / last visit,
  the card (contact, notes, open tab, every visit with what was on a tab), new/edit/remove
- Inventory -> Throwaways: log (product, quantity with a comma, reason, note) with its cost, today's list (delete today only),
  a period's totals by reason and product, every entry; Inventory -> Stock: an honest 'not available yet'
- Notes: notes (pinned first, edit in place) and to-dos (urgent first, done folded away, who did it kept)
- backend: crm.manage / inventory.manage / notes.use (the customer search also with the dashboard key, for orders);
  spending counted by services/sales.py (refunds off, tab lines in); null clears a field; names/notes not blank, priorities checked;
  waste ?date_from=&date_to= venue dates; the Greek reason labels left the API; live customers.changed / waste.changed / notes.changed
- the overview's notes card needs notes.use and refreshes live
- tests: test_customers_waste_notes.py (4), crm.test.mjs (3), e2e manager.mjs (customers, throwaways, notes, stock, Greek)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 18:36:27 +02:00
co-authored by Claude Opus 5.5
parent 07c9a0aecf
commit bde125bf09
28 changed files with 1356 additions and 1244 deletions
+2 -2
View File
@@ -22,7 +22,7 @@ import QrCodesPage from './pages/online/QrCodesPage'
// CRM
import ContactsPage from './pages/finance/ContactsPage'
import CustomersPage from './pages/crm/CustomersPage'
import CustomersPage from './pages/customers/CustomersPage'
// Financials
import ExpensesPage from './pages/finance/ExpensesPage'
@@ -60,7 +60,7 @@ import LicensePage from './pages/platform/LicensePage'
import DevicesPage from './pages/platform/DevicesPage'
import PhonePage from './pages/PhonePage'
import SettingsPage from './pages/Settings/SettingsPage'
import NotesPage from './pages/NotesPage'
import NotesPage from './pages/notes/NotesPage'
// Texts for the shared parts (approval dialog, "feature off" screens, component labels).
// The language follows bootstrap (user -> venue); the current pages are still Greek (phase 6).
@@ -1,349 +0,0 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
// ── Helpers ───────────────────────────────────────────────────────────────────
function fmt(n) {
if (n == null) return '—'
return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
}
function fmtDate(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit', year: 'numeric' })
}
function fmtDateTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
}
const ORDER_STATUS_LABELS = {
closed: 'Κλειστή', paid: 'Πληρωμένη', open: 'Ανοιχτή',
partially_paid: 'Μερική πλ.', cancelled: 'Ακυρωμένη',
}
const ORDER_STATUS_COLORS = {
closed: '#6b7280', paid: '#16a34a', open: '#3b82f6',
partially_paid: '#d97706', cancelled: '#ef4444',
}
const inputStyle = {
width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
}
// ── Customer modal (create / edit) ───────────────────────────────────────────
const EMPTY_FORM = { name: '', nickname: '', phone: '', email: '', notes: '' }
function CustomerModal({ initial, onClose, onSave, isPending }) {
const [form, setForm] = useState(initial ?? EMPTY_FORM)
const f = (k, v) => setForm(p => ({ ...p, [k]: v }))
const isNew = !initial?.id
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 480, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{isNew ? 'Νέος Πελάτης' : 'Επεξεργασία Πελάτη'}</h2>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Όνομα *</label>
<input style={inputStyle} value={form.name} onChange={e => f('name', e.target.value)} autoFocus placeholder="π.χ. Γιώργος Παπαδόπουλος" />
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Παρατσούκλι</label>
<input style={inputStyle} value={form.nickname} onChange={e => f('nickname', e.target.value)} placeholder="π.χ. Μεγάλος Γιάννης" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Τηλέφωνο</label>
<input style={inputStyle} value={form.phone} onChange={e => f('phone', e.target.value)} placeholder="π.χ. 6912345678" />
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Email</label>
<input style={inputStyle} type="email" value={form.email} onChange={e => f('email', e.target.value)} placeholder="email@example.com" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημειώσεις <span style={{ fontWeight: 400, color: '#9ca3af' }}>(αλλεργίες, προτιμήσεις…)</span></label>
<textarea style={{ ...inputStyle, resize: 'none' }} rows={3} value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="π.χ. Αλλεργία στους ξηρούς καρπούς, VIP πελάτης…" />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button
onClick={() => onSave(form)}
disabled={!form.name.trim() || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: form.name.trim() ? 'pointer' : 'default', background: form.name.trim() ? '#111827' : '#e5e7eb', color: form.name.trim() ? 'white' : '#9ca3af' }}
>
{isPending ? 'Αποθήκευση…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
</button>
</div>
</div>
</div>
)
}
// ── Customer detail panel ─────────────────────────────────────────────────────
function CustomerDetail({ customer, onEdit, onClose }) {
const { data, isLoading } = useQuery({
queryKey: ['customer-orders', customer.id],
queryFn: () => client.get(`/api/customers/${customer.id}/orders`).then(r => r.data),
staleTime: 30_000,
})
const { data: tabsData = [] } = useQuery({
queryKey: ['customer-tabs', customer.id],
queryFn: () => client.get(`/api/tabs/customer/${customer.id}`).then(r => r.data),
staleTime: 30_000,
})
const openTab = tabsData.find(t => t.status === 'open')
const orders = data?.orders || []
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'white', borderLeft: '1px solid #f0f0ef' }}>
{/* Header */}
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexShrink: 0 }}>
<div>
<div style={{ fontSize: 18, fontWeight: 800, color: '#111315' }}>{customer.name}</div>
{customer.nickname && <div style={{ fontSize: 13, color: '#9ca3af', marginTop: 2 }}>«{customer.nickname}»</div>}
</div>
<div style={{ display: 'flex', gap: 6 }}>
<button onClick={onEdit} style={{ padding: '5px 12px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 7, fontSize: 12, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>Επεξεργασία</button>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af', padding: '0 4px' }}>✕</button>
</div>
</div>
{/* Stats row */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, padding: '14px 22px', flexShrink: 0, borderBottom: '1px solid #f0f0ef' }}>
{[
{ label: 'Επισκέψεις', value: customer.visit_count },
{ label: 'Σύνολο εξόδων', value: fmt(customer.total_spent) },
{ label: 'Μέσος λογ.', value: customer.visit_count > 0 ? fmt(customer.total_spent / customer.visit_count) : '—' },
].map(s => (
<div key={s.label} style={{ background: '#f9fafb', borderRadius: 10, padding: '10px 12px', textAlign: 'center' }}>
<div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
<div style={{ fontSize: 16, fontWeight: 800, color: '#111315', marginTop: 3 }}>{s.value}</div>
</div>
))}
</div>
{/* Open tab banner */}
{openTab && (
<div style={{ padding: '10px 22px', borderBottom: '1px solid #f0f0ef', flexShrink: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 10 }}>
<div>
<div style={{ fontSize: 12.5, fontWeight: 700, color: '#dc2626' }}>Ανοιχτή Καρτέλα</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 1 }}>
{openTab.entries.length} χρεώσεις · πληρωμένο {fmt(openTab.total_paid)}
</div>
</div>
<div style={{ fontSize: 18, fontWeight: 800, color: '#dc2626' }}>{fmt(openTab.balance)}</div>
</div>
</div>
)}
{/* Contact info */}
<div style={{ padding: '12px 22px', borderBottom: '1px solid #f0f0ef', flexShrink: 0 }}>
{(customer.phone || customer.email || customer.notes) ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 13 }}>
{customer.phone && <div><span style={{ color: '#9ca3af', marginRight: 6 }}>📞</span>{customer.phone}</div>}
{customer.email && <div><span style={{ color: '#9ca3af', marginRight: 6 }}>✉</span>{customer.email}</div>}
{customer.notes && (
<div style={{ marginTop: 4, padding: '8px 12px', background: '#fffbeb', borderRadius: 8, border: '1px solid #fef3c7', fontSize: 12.5, color: '#92400e', lineHeight: 1.5 }}>
📝 {customer.notes}
</div>
)}
</div>
) : (
<div style={{ fontSize: 12.5, color: '#d1d5db' }}>Δεν υπάρχουν στοιχεία επικοινωνίας.</div>
)}
</div>
{/* Visit history */}
<div style={{ flex: 1, overflowY: 'auto', padding: '14px 22px' }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10 }}>Ιστορικό Επισκέψεων</div>
{isLoading && <div style={{ color: '#9ca3af', fontSize: 13 }}>Φόρτωση…</div>}
{!isLoading && orders.length === 0 && (
<div style={{ color: '#d1d5db', fontSize: 13 }}>Δεν υπάρχουν επισκέψεις ακόμα.</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{orders.map(o => (
<div key={o.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', border: '1px solid #f0f0ef', borderRadius: 10, background: 'white' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: '#111315' }}>
{o.table_name ? `Τραπέζι ${o.table_name}` : 'Χωρίς τραπέζι'}
{' '}
<span style={{ fontSize: 11, fontWeight: 700, padding: '1px 6px', borderRadius: 99, background: '#f3f4f6', color: ORDER_STATUS_COLORS[o.status] || '#6b7280' }}>
{ORDER_STATUS_LABELS[o.status] || o.status}
</span>
</div>
<div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 1 }}>
{fmtDateTime(o.opened_at)} · {o.item_count} αντικ.
</div>
</div>
<div style={{ fontSize: 14, fontWeight: 700, color: '#111315', whiteSpace: 'nowrap' }}>{fmt(o.total)}</div>
</div>
))}
</div>
</div>
</div>
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function CustomersPage() {
const qc = useQueryClient()
const [search, setSearch] = useState('')
const [selected, setSelected] = useState(null) // customer being viewed
const [modal, setModal] = useState(null) // null | { customer } | { customer: null }
const { data: customers = [], isLoading } = useQuery({
queryKey: ['customers', search],
queryFn: () => client.get('/api/customers/', { params: search ? { search } : {} }).then(r => r.data),
staleTime: 30_000,
})
const save = useMutation({
mutationFn: ({ form, id }) => id
? client.put(`/api/customers/${id}`, form)
: client.post('/api/customers/', form),
onSuccess: (res) => {
qc.invalidateQueries({ queryKey: ['customers'] })
if (selected && res.data?.id === selected.id) {
setSelected(res.data)
}
setModal(null)
toast.success('Αποθηκεύτηκε')
},
onError: () => toast.error('Σφάλμα αποθήκευσης'),
})
const deactivate = useMutation({
mutationFn: (id) => client.delete(`/api/customers/${id}`),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['customers'] })
if (selected?.id) setSelected(null)
toast.success('Αποενεργοποιήθηκε')
},
onError: () => toast.error('Σφάλμα'),
})
const activeCount = customers.length
return (
<div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
{/* Left: list */}
<div style={{ display: 'flex', flexDirection: 'column', width: selected ? 360 : '100%', flexShrink: 0, borderRight: selected ? '1px solid #f0f0ef' : 'none', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '18px 24px 14px', borderBottom: '1px solid #f0f0ef', flexShrink: 0, background: 'white' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>{activeCount} ενεργοί πελάτες</p>
</div>
<button
onClick={() => setModal({ customer: null })}
style={{ padding: '8px 16px', borderRadius: 9, border: 'none', background: '#111827', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
>
+ Νέος
</button>
</div>
<input
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Αναζήτηση με όνομα, παρατσούκλι ή τηλέφωνο…"
style={{ ...inputStyle, fontSize: 13 }}
/>
</div>
{/* List */}
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 4 }}>
{isLoading && <div style={{ color: '#9ca3af', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>Φόρτωση…</div>}
{!isLoading && customers.length === 0 && (
<div style={{ color: '#9ca3af', fontSize: 13, textAlign: 'center', padding: '32px 0' }}>
{search ? 'Δεν βρέθηκαν αποτελέσματα.' : 'Δεν υπάρχουν πελάτες ακόμα.'}
</div>
)}
{customers.map(c => (
<button
key={c.id}
onClick={() => setSelected(selected?.id === c.id ? null : c)}
style={{
display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
border: `1px solid ${selected?.id === c.id ? '#3b82f6' : '#f0f0ef'}`,
borderRadius: 10, background: selected?.id === c.id ? '#eff6ff' : 'white',
cursor: 'pointer', textAlign: 'left', width: '100%',
}}
>
{/* Avatar */}
<div style={{
width: 38, height: 38, borderRadius: '50%', flexShrink: 0,
background: `hsl(${[...c.name].reduce((a, ch) => a + ch.charCodeAt(0), 0) % 360},55%,62%)`,
color: 'white', fontSize: 15, fontWeight: 700,
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{c.name.trim()[0].toUpperCase()}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: '#111315', display: 'flex', alignItems: 'center', gap: 6 }}>
{c.name}
{c.nickname && <span style={{ fontSize: 11, fontWeight: 500, color: '#9ca3af' }}>«{c.nickname}»</span>}
</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 1 }}>
{c.phone || c.email || 'Χωρίς στοιχεία'}
{c.visit_count > 0 && <span style={{ marginLeft: 8, color: '#6b7280' }}>· {c.visit_count} επισκέψεις</span>}
</div>
</div>
<div style={{ fontSize: 13, fontWeight: 700, color: '#111315', whiteSpace: 'nowrap', flexShrink: 0 }}>
{c.total_spent > 0 ? fmt(c.total_spent) : ''}
</div>
</button>
))}
</div>
</div>
{/* Right: detail panel */}
{selected && (
<div style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
<CustomerDetail
customer={selected}
onEdit={() => setModal({ customer: selected })}
onClose={() => setSelected(null)}
/>
</div>
)}
{modal && (
<CustomerModal
initial={modal.customer ? {
...modal.customer,
nickname: modal.customer.nickname || '',
phone: modal.customer.phone || '',
email: modal.customer.email || '',
notes: modal.customer.notes || '',
} : null}
onClose={() => setModal(null)}
isPending={save.isPending}
onSave={(form) => save.mutate({
form: {
name: form.name,
nickname: form.nickname || null,
phone: form.phone || null,
email: form.email || null,
notes: form.notes || null,
},
id: modal.customer?.id,
})}
/>
)}
</div>
)
}
-500
View File
@@ -1,500 +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'
// ── helpers ───────────────────────────────────────────────────────────────────
function fmtDate(iso) {
if (!iso) return ''
const d = new Date(iso)
const now = new Date()
const diffMs = now - d
const diffMins = Math.floor(diffMs / 60000)
if (diffMins < 1) return 'μόλις τώρα'
if (diffMins < 60) return `${diffMins}λ πριν`
const diffH = Math.floor(diffMins / 60)
if (diffH < 24) return `${diffH}ω πριν`
return d.toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit' })
}
// ── Notes column ──────────────────────────────────────────────────────────────
function NoteCard({ note, onSave, onDelete, onTogglePin }) {
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState(note.body)
const taRef = useRef(null)
useEffect(() => {
if (editing && taRef.current) {
taRef.current.focus()
taRef.current.selectionStart = taRef.current.value.length
}
}, [editing])
function handleBlur() {
if (draft.trim() === note.body) { setEditing(false); return }
if (!draft.trim()) { setEditing(false); setDraft(note.body); return }
onSave(note.id, draft.trim())
setEditing(false)
}
function handleKeyDown(e) {
if (e.key === 'Escape') { setEditing(false); setDraft(note.body) }
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleBlur()
}
return (
<div style={{
border: note.is_pinned ? '1.5px solid #fbbf24' : '1px solid #e5e7eb',
borderRadius: 12,
background: note.is_pinned ? '#fffbeb' : 'white',
padding: '14px 16px',
display: 'flex',
flexDirection: 'column',
gap: 8,
}}>
{editing ? (
<textarea
ref={taRef}
value={draft}
onChange={e => setDraft(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
style={{
width: '100%', minHeight: 80, border: '1.5px solid #3b82f6',
borderRadius: 8, padding: '8px 10px', fontSize: 13.5, lineHeight: 1.55,
resize: 'vertical', outline: 'none', fontFamily: 'inherit',
background: 'white',
}}
/>
) : (
<p
onClick={() => { setEditing(true); setDraft(note.body) }}
style={{
fontSize: 13.5, color: '#111827', lineHeight: 1.6, cursor: 'text',
whiteSpace: 'pre-wrap', margin: 0, wordBreak: 'break-word',
}}
>
{note.body}
</p>
)}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span style={{ fontSize: 11, color: '#9ca3af' }}>
{note.created_by_name} · {fmtDate(note.updated_at)}
</span>
<div style={{ display: 'flex', gap: 4 }}>
<button
onClick={() => onTogglePin(note.id, !note.is_pinned)}
title={note.is_pinned ? 'Αποσύνδεση' : 'Καρφίτσωμα'}
style={{
fontSize: 13, padding: '2px 7px', borderRadius: 6, border: '1px solid #e5e7eb',
background: note.is_pinned ? '#fef3c7' : 'white', cursor: 'pointer',
color: note.is_pinned ? '#d97706' : '#6b7280',
}}
>
{note.is_pinned ? '📌' : '📍'}
</button>
<button
onClick={() => { if (window.confirm('Διαγραφή σημείωσης;')) onDelete(note.id) }}
style={{
fontSize: 12, padding: '2px 7px', borderRadius: 6,
border: '1px solid #fecaca', background: 'white',
color: '#ef4444', cursor: 'pointer',
}}
>✕</button>
</div>
</div>
</div>
)
}
function NotesColumn({ notes, onAdd, onSave, onDelete, onTogglePin }) {
const [newBody, setNewBody] = useState('')
const [newPinned, setNewPinned] = useState(false)
function submit() {
if (!newBody.trim()) return
onAdd(newBody.trim(), newPinned)
setNewBody('')
setNewPinned(false)
}
function onKeyDown(e) {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit()
}
const pinned = notes.filter(n => n.is_pinned)
const rest = notes.filter(n => !n.is_pinned)
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%' }}>
{/* New note form */}
<div style={{ border: '1.5px dashed #d1d5db', borderRadius: 12, padding: '12px 14px', background: '#fafafa' }}>
<textarea
value={newBody}
onChange={e => setNewBody(e.target.value)}
onKeyDown={onKeyDown}
placeholder="Νέα σημείωση… (Ctrl+Enter για αποθήκευση)"
style={{
width: '100%', minHeight: 72, border: 'none', outline: 'none',
background: 'transparent', fontSize: 13.5, lineHeight: 1.55,
resize: 'none', fontFamily: 'inherit', color: '#374151',
}}
/>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 6 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#6b7280', cursor: 'pointer' }}>
<input type="checkbox" checked={newPinned} onChange={e => setNewPinned(e.target.checked)} />
Καρφίτσωμα
</label>
<button
onClick={submit}
disabled={!newBody.trim()}
style={{
padding: '5px 14px', borderRadius: 7, border: 'none',
background: newBody.trim() ? '#111827' : '#e5e7eb',
color: newBody.trim() ? 'white' : '#9ca3af',
fontSize: 12.5, fontWeight: 600, cursor: newBody.trim() ? 'pointer' : 'default',
}}
>
Αποθήκευση
</button>
</div>
</div>
{/* Notes list */}
<div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
{pinned.length > 0 && (
<>
<div style={{ fontSize: 10, fontWeight: 700, color: '#d97706', textTransform: 'uppercase', letterSpacing: '0.06em' }}>📌 Καρφιτσωμένες</div>
{pinned.map(n => (
<NoteCard key={n.id} note={n} onSave={onSave} onDelete={onDelete} onTogglePin={onTogglePin} />
))}
</>
)}
{rest.length > 0 && (
<>
{pinned.length > 0 && <div style={{ fontSize: 10, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 4 }}>Πρόσφατες</div>}
{rest.map(n => (
<NoteCard key={n.id} note={n} onSave={onSave} onDelete={onDelete} onTogglePin={onTogglePin} />
))}
</>
)}
{notes.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '32px 0' }}>
Δεν υπάρχουν σημειώσεις ακόμα.
</div>
)}
</div>
</div>
)
}
// ── Todos column ──────────────────────────────────────────────────────────────
function TodoItem({ todo, onToggle, onDelete, onEdit }) {
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState(todo.body)
const inputRef = useRef(null)
useEffect(() => {
if (editing && inputRef.current) inputRef.current.focus()
}, [editing])
function saveEdit() {
if (!draft.trim() || draft.trim() === todo.body) { setEditing(false); setDraft(todo.body); return }
onEdit(todo.id, draft.trim())
setEditing(false)
}
return (
<div style={{
display: 'flex', alignItems: 'flex-start', gap: 10,
padding: '10px 12px', borderRadius: 10,
border: `1px solid ${todo.is_done ? '#e5e7eb' : todo.priority === 'high' ? '#fca5a5' : '#e5e7eb'}`,
background: todo.is_done ? '#fafafa' : todo.priority === 'high' ? '#fff5f5' : 'white',
opacity: todo.is_done ? 0.65 : 1,
}}>
{/* Checkbox */}
<button
onClick={() => onToggle(todo.id, !todo.is_done)}
style={{
width: 20, height: 20, borderRadius: 5, flexShrink: 0, marginTop: 1,
border: `2px solid ${todo.is_done ? '#22c55e' : todo.priority === 'high' ? '#ef4444' : '#d1d5db'}`,
background: todo.is_done ? '#22c55e' : 'white',
cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>
{todo.is_done && <span style={{ color: 'white', fontSize: 11, lineHeight: 1 }}>✓</span>}
</button>
{/* Body */}
<div style={{ flex: 1, minWidth: 0 }}>
{editing ? (
<input
ref={inputRef}
value={draft}
onChange={e => setDraft(e.target.value)}
onBlur={saveEdit}
onKeyDown={e => { if (e.key === 'Enter') saveEdit(); if (e.key === 'Escape') { setEditing(false); setDraft(todo.body) } }}
style={{
width: '100%', border: '1.5px solid #3b82f6', borderRadius: 6,
padding: '3px 7px', fontSize: 13.5, outline: 'none', fontFamily: 'inherit',
}}
/>
) : (
<p
onClick={() => { if (!todo.is_done) { setEditing(true); setDraft(todo.body) } }}
style={{
margin: 0, fontSize: 13.5, lineHeight: 1.5, wordBreak: 'break-word',
color: todo.is_done ? '#9ca3af' : '#111827',
textDecoration: todo.is_done ? 'line-through' : 'none',
cursor: todo.is_done ? 'default' : 'text',
}}
>
{todo.priority === 'high' && !todo.is_done && (
<span style={{ fontSize: 11, fontWeight: 700, color: '#ef4444', marginRight: 5 }}>● ΕΠΕΙΓΟΝ</span>
)}
{todo.body}
</p>
)}
<div style={{ fontSize: 11, color: '#9ca3af', marginTop: 3 }}>
{todo.created_by_name} · {fmtDate(todo.created_at)}
{todo.is_done && todo.done_by_name && (
<span style={{ color: '#22c55e' }}> · ✓ {todo.done_by_name}</span>
)}
</div>
</div>
{/* Delete */}
<button
onClick={() => { if (window.confirm('Διαγραφή εργασίας;')) onDelete(todo.id) }}
style={{
fontSize: 11, padding: '2px 6px', borderRadius: 5, flexShrink: 0,
border: '1px solid #fecaca', background: 'white', color: '#ef4444', cursor: 'pointer',
}}
>✕</button>
</div>
)
}
function TodosColumn({ todos, onAdd, onToggle, onDelete, onEdit }) {
const [newBody, setNewBody] = useState('')
const [newPriority, setNewPriority] = useState('normal')
const [showDone, setShowDone] = useState(false)
function submit() {
if (!newBody.trim()) return
onAdd(newBody.trim(), newPriority)
setNewBody('')
setNewPriority('normal')
}
const undone = todos.filter(t => !t.is_done)
const done = todos.filter(t => t.is_done)
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%' }}>
{/* New todo form */}
<div style={{ border: '1.5px dashed #d1d5db', borderRadius: 12, padding: '12px 14px', background: '#fafafa' }}>
<input
value={newBody}
onChange={e => setNewBody(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') submit() }}
placeholder="Νέα εργασία… (Enter)"
style={{
width: '100%', border: 'none', outline: 'none', background: 'transparent',
fontSize: 13.5, fontFamily: 'inherit', color: '#374151',
}}
/>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
<div style={{ display: 'flex', gap: 6 }}>
{['normal', 'high'].map(p => (
<button
key={p}
onClick={() => setNewPriority(p)}
style={{
padding: '3px 10px', borderRadius: 6, fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
border: `1.5px solid ${newPriority === p ? (p === 'high' ? '#ef4444' : '#6b7280') : '#e5e7eb'}`,
background: newPriority === p ? (p === 'high' ? '#fee2e2' : '#f3f4f6') : 'white',
color: newPriority === p ? (p === 'high' ? '#ef4444' : '#374151') : '#9ca3af',
}}
>
{p === 'high' ? '● Επείγον' : 'Κανονικό'}
</button>
))}
</div>
<button
onClick={submit}
disabled={!newBody.trim()}
style={{
padding: '5px 14px', borderRadius: 7, border: 'none',
background: newBody.trim() ? '#111827' : '#e5e7eb',
color: newBody.trim() ? 'white' : '#9ca3af',
fontSize: 12.5, fontWeight: 600, cursor: newBody.trim() ? 'pointer' : 'default',
}}
>
Προσθήκη
</button>
</div>
</div>
{/* Todo list */}
<div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
{undone.length === 0 && done.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '32px 0' }}>
Δεν υπάρχουν εργασίες ακόμα.
</div>
)}
{undone.map(t => (
<TodoItem key={t.id} todo={t} onToggle={onToggle} onDelete={onDelete} onEdit={onEdit} />
))}
{done.length > 0 && (
<button
onClick={() => setShowDone(s => !s)}
style={{
marginTop: 4, fontSize: 12, color: '#9ca3af', fontWeight: 600,
background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', padding: '4px 0',
}}
>
{showDone ? '▾' : '▸'} Ολοκληρωμένες ({done.length})
</button>
)}
{showDone && done.map(t => (
<TodoItem key={t.id} todo={t} onToggle={onToggle} onDelete={onDelete} onEdit={onEdit} />
))}
</div>
</div>
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function NotesPage() {
const qc = useQueryClient()
const { data: notes = [] } = useQuery({
queryKey: ['site-notes'],
queryFn: () => client.get('/api/notes/').then(r => r.data),
staleTime: 30_000,
})
const { data: todos = [] } = useQuery({
queryKey: ['site-todos'],
queryFn: () => client.get('/api/notes/todos').then(r => r.data),
staleTime: 30_000,
})
// ── Note mutations ──────────────────────────────────────────────────────────
const addNote = useMutation({
mutationFn: ({ body, is_pinned }) => client.post('/api/notes/', { body, is_pinned }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
onError: () => toast.error('Σφάλμα αποθήκευσης'),
})
const saveNote = useMutation({
mutationFn: ({ id, body }) => client.put(`/api/notes/${id}`, { body }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
onError: () => toast.error('Σφάλμα αποθήκευσης'),
})
const pinNote = useMutation({
mutationFn: ({ id, is_pinned }) => client.put(`/api/notes/${id}`, { is_pinned }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
})
const deleteNote = useMutation({
mutationFn: (id) => client.delete(`/api/notes/${id}`),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
onError: () => toast.error('Σφάλμα διαγραφής'),
})
// ── Todo mutations ──────────────────────────────────────────────────────────
const addTodo = useMutation({
mutationFn: ({ body, priority }) => client.post('/api/notes/todos', { body, priority }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
onError: () => toast.error('Σφάλμα αποθήκευσης'),
})
const toggleTodo = useMutation({
mutationFn: ({ id, is_done }) => client.put(`/api/notes/todos/${id}`, { is_done }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
})
const editTodo = useMutation({
mutationFn: ({ id, body }) => client.put(`/api/notes/todos/${id}`, { body }),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
onError: () => toast.error('Σφάλμα αποθήκευσης'),
})
const deleteTodo = useMutation({
mutationFn: (id) => client.delete(`/api/notes/todos/${id}`),
onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
onError: () => toast.error('Σφάλμα διαγραφής'),
})
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Page header */}
<div style={{
padding: '18px 28px 14px',
borderBottom: '1px solid #f0f0ef',
display: 'flex', alignItems: 'baseline', gap: 16, flexShrink: 0,
background: 'white',
}}>
<span style={{ fontSize: 13, color: '#9ca3af' }}>
{notes.length} σημειώσεις · {todos.filter(t => !t.is_done).length} εκκρεμείς εργασίες
</span>
</div>
{/* Two-column body */}
<div style={{
display: 'grid', gridTemplateColumns: '1fr 1fr',
gap: 0, flex: 1, overflow: 'hidden',
}}>
{/* Left: Notes */}
<div style={{
borderRight: '1px solid #f0f0ef',
padding: '20px 24px',
display: 'flex', flexDirection: 'column', overflow: 'hidden',
}}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12 }}>
Σημειώσεις
</div>
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
<NotesColumn
notes={notes}
onAdd={(body, is_pinned) => addNote.mutate({ body, is_pinned })}
onSave={(id, body) => saveNote.mutate({ id, body })}
onDelete={(id) => deleteNote.mutate(id)}
onTogglePin={(id, is_pinned) => pinNote.mutate({ id, is_pinned })}
/>
</div>
</div>
{/* Right: Todos */}
<div style={{
padding: '20px 24px',
display: 'flex', flexDirection: 'column', overflow: 'hidden',
}}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12 }}>
Εργασίες
</div>
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
<TodosColumn
todos={todos}
onAdd={(body, priority) => addTodo.mutate({ body, priority })}
onToggle={(id, is_done) => toggleTodo.mutate({ id, is_done })}
onEdit={(id, body) => editTodo.mutate({ id, body })}
onDelete={(id) => deleteTodo.mutate(id)}
/>
</div>
</div>
</div>
</div>
)
}
-295
View File
@@ -1,295 +0,0 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
// ── Constants ─────────────────────────────────────────────────────────────────
const REASONS = [
{ id: 'kitchen_error', label: 'Λάθος κουζίνας', color: '#dc2626' },
{ id: 'dropped', label: 'Έπεσε', color: '#d97706' },
{ id: 'expired', label: 'Έληξε', color: '#7c3aed' },
{ id: 'other', label: 'Άλλο', color: '#6b7280' },
]
// ── Helpers ───────────────────────────────────────────────────────────────────
function fmt(n) {
if (n == null) return '—'
return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
}
function fmtDateTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
}
// ── Log form ──────────────────────────────────────────────────────────────────
function LogForm({ products, onLog, isPending }) {
const [productId, setProductId] = useState('')
const [qty, setQty] = useState('1')
const [reason, setReason] = useState('kitchen_error')
const [notes, setNotes] = useState('')
const canLog = productId && parseFloat(qty) > 0
function submit() {
if (!canLog) return
onLog({
product_id: Number(productId),
quantity: parseFloat(qty),
reason,
reason_notes: notes.trim() || null,
})
setProductId('')
setQty('1')
setReason('kitchen_error')
setNotes('')
}
const inputStyle = {
width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
boxSizing: 'border-box',
}
return (
<div style={{ border: '1.5px dashed #d1d5db', borderRadius: 14, padding: '16px 20px', background: '#fafafa' }}>
<div style={{ fontSize: 12, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 14 }}>
Καταγραφή Απόβλητου
</div>
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 10, marginBottom: 10 }}>
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Προϊόν *</label>
<select style={inputStyle} value={productId} onChange={e => setProductId(e.target.value)} autoFocus>
<option value="">— Επιλέξτε προϊόν —</option>
{products.map(p => (
<option key={p.id} value={p.id}>{p.name}{p.category_name ? ` (${p.category_name})` : ''}</option>
))}
</select>
</div>
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Ποσότητα *</label>
<input type="number" step="0.5" min="0.1"
style={inputStyle} value={qty} onChange={e => setQty(e.target.value)} />
</div>
</div>
<div style={{ marginBottom: 10 }}>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 6 }}>Αιτία</label>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
{REASONS.map(r => (
<button key={r.id} type="button" onClick={() => setReason(r.id)}
style={{
padding: '5px 12px', borderRadius: 20, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
border: `1.5px solid ${reason === r.id ? r.color : '#e5e7eb'}`,
background: reason === r.id ? r.color : 'white',
color: reason === r.id ? 'white' : '#6b7280',
}}>
{r.label}
</button>
))}
</div>
</div>
<div style={{ marginBottom: 14 }}>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>
Σημείωση <span style={{ fontWeight: 400, color: '#9ca3af' }}>(προαιρετική)</span>
</label>
<input style={inputStyle} value={notes} onChange={e => setNotes(e.target.value)}
placeholder="π.χ. Ο πελάτης επέστρεψε ελαττωματικό…" />
</div>
<button onClick={submit} disabled={!canLog || isPending}
style={{
padding: '9px 22px', borderRadius: 9, border: 'none', fontSize: 13.5, fontWeight: 700, cursor: canLog ? 'pointer' : 'default',
background: canLog ? '#111827' : '#e5e7eb', color: canLog ? 'white' : '#9ca3af',
}}>
{isPending ? 'Καταγραφή…' : '+ Καταγραφή Απόβλητου'}
</button>
</div>
)
}
// ── Waste entry row ───────────────────────────────────────────────────────────
function WasteRow({ entry, canDelete, onDelete }) {
const reasonCfg = REASONS.find(r => r.id === entry.reason) || { label: entry.reason, color: '#6b7280' }
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 16px', border: '1px solid #f0f0ef', borderRadius: 10, background: 'white' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: '#111315', display: 'flex', alignItems: 'center', gap: 8 }}>
{entry.product_name}
<span style={{ fontSize: 13, fontWeight: 700, color: '#374151' }}>×{entry.quantity}</span>
<span style={{ fontSize: 11, fontWeight: 700, padding: '1px 7px', borderRadius: 99, background: `${reasonCfg.color}18`, color: reasonCfg.color }}>
{reasonCfg.label}
</span>
</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 2 }}>
{fmtDateTime(entry.logged_at)} · {entry.logged_by_name}
{entry.reason_notes && <span style={{ color: '#6b7280', marginLeft: 8 }}>— {entry.reason_notes}</span>}
</div>
</div>
<div style={{ textAlign: 'right', flexShrink: 0 }}>
{entry.total_cost != null ? (
<div style={{ fontSize: 13.5, fontWeight: 700, color: '#dc2626' }}>{fmt(entry.total_cost)}</div>
) : (
<div style={{ fontSize: 12, color: '#d1d5db' }}>χωρίς κόστος</div>
)}
{entry.unit_cost_snapshot != null && (
<div style={{ fontSize: 11, color: '#9ca3af' }}>{fmt(entry.unit_cost_snapshot)}/τεμ.</div>
)}
</div>
{canDelete && (
<button onClick={() => { if (window.confirm('Διαγραφή καταχώρησης;')) onDelete(entry.id) }}
style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid #fecaca', background: 'white', color: '#ef4444', fontSize: 12, cursor: 'pointer', flexShrink: 0 }}>
✕
</button>
)}
</div>
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function WastePage() {
const qc = useQueryClient()
const [showHistory, setShowHistory] = useState(false)
const [histFrom, setHistFrom] = useState(() => new Date().toISOString().slice(0, 10))
const [histTo, setHistTo] = useState(() => new Date().toISOString().slice(0, 10))
const { data: productsData = [] } = useQuery({
queryKey: ['meta-products'],
queryFn: () => client.get('/api/reports/meta/products').then(r => r.data.products),
staleTime: 5 * 60_000,
})
const { data: bdData } = useQuery({
queryKey: ['business-day'],
queryFn: () => client.get('/api/business-day/current').then(r => r.data),
staleTime: 30_000,
})
const activeDayId = bdData?.id ?? null
// Today's entries — scoped to active business day (or all if no active day)
const { data: todayData } = useQuery({
queryKey: ['waste-today', activeDayId],
queryFn: () => client.get('/api/waste/', { params: activeDayId ? { business_day_id: activeDayId } : {} }).then(r => r.data),
staleTime: 15_000,
})
// Historical entries
const { data: histData, refetch: refetchHist } = useQuery({
queryKey: ['waste-history', histFrom, histTo],
queryFn: () => client.get('/api/waste/', { params: { from: histFrom + 'T00:00:00', to: histTo + 'T23:59:59' } }).then(r => r.data),
staleTime: 30_000,
enabled: showHistory,
})
const todayEntries = todayData?.entries || []
const histEntries = histData?.entries || []
const todayCost = todayEntries.reduce((s, e) => s + (e.total_cost || 0), 0)
const todayCount = todayEntries.length
const logWaste = useMutation({
mutationFn: (body) => client.post('/api/waste/', body),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['waste-today'] })
qc.invalidateQueries({ queryKey: ['waste-history'] })
toast.success('Καταγράφηκε')
},
onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
})
const deleteWaste = useMutation({
mutationFn: (id) => client.delete(`/api/waste/${id}`),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['waste-today'] })
qc.invalidateQueries({ queryKey: ['waste-history'] })
toast.success('Διαγράφηκε')
},
onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
})
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '18px 28px 14px', borderBottom: '1px solid #f0f0ef', flexShrink: 0, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>
Σήμερα: {todayCount} καταχωρήσεις
{todayCost > 0 && <span style={{ color: '#dc2626', fontWeight: 600 }}> · εκτιμώμενο κόστος {todayCost.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €</span>}
</p>
</div>
</div>
<div style={{ flex: 1, overflowY: 'auto', padding: '16px 28px', display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* Log form */}
<LogForm products={productsData} onLog={body => logWaste.mutate(body)} isPending={logWaste.isPending} />
{/* Today's entries */}
<div>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>
{activeDayId ? 'Σήμερα' : 'Τελευταίες καταχωρήσεις'}
</div>
{todayEntries.length === 0 ? (
<div style={{ textAlign: 'center', color: '#d1d5db', fontSize: 13, padding: '20px 0' }}>Καμία καταχώρηση ακόμα.</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{todayEntries.map(e => (
<WasteRow key={e.id} entry={e} canDelete={!!activeDayId} onDelete={id => deleteWaste.mutate(id)} />
))}
</div>
)}
</div>
{/* History toggle */}
<div style={{ borderTop: '1px solid #f0f0ef', paddingTop: 12 }}>
<button onClick={() => setShowHistory(s => !s)}
style={{ fontSize: 13, fontWeight: 600, color: '#6b7280', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
{showHistory ? '▾ Απόκρυψη ιστορικού' : '▸ Εμφάνιση ιστορικού'}
</button>
{showHistory && (
<div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
<div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<label style={{ fontSize: 12, color: '#6b7280', fontWeight: 600 }}>Από</label>
<input type="date" value={histFrom} onChange={e => setHistFrom(e.target.value)}
style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<label style={{ fontSize: 12, color: '#6b7280', fontWeight: 600 }}>Έως</label>
<input type="date" value={histTo} onChange={e => setHistTo(e.target.value)}
style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
</div>
<button onClick={() => refetchHist()}
style={{ padding: '5px 14px', borderRadius: 7, border: '1px solid #e5e7eb', background: 'white', fontSize: 12.5, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>
Αναζήτηση
</button>
</div>
{histEntries.length === 0 ? (
<div style={{ color: '#d1d5db', fontSize: 13, padding: '12px 0' }}>Δεν βρέθηκαν καταχωρήσεις.</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{histEntries.map(e => (
<WasteRow key={e.id} entry={e} canDelete={false} onDelete={() => {}} />
))}
<div style={{ fontSize: 12.5, color: '#6b7280', fontWeight: 600, paddingLeft: 4 }}>
{histEntries.length} καταχωρήσεις · εκτιμώμενο κόστος{' '}
<span style={{ color: '#dc2626' }}>
{histEntries.reduce((s, e) => s + (e.total_cost || 0), 0).toLocaleString('el-GR', { minimumFractionDigits: 2 })} €
</span>
</div>
</div>
)}
</div>
)}
</div>
</div>
</div>
)
}
@@ -1 +0,0 @@
export { default } from '../CustomersPage'
@@ -0,0 +1,83 @@
// A customer's card (plan step 6.13b): visits, spent, per visit; phone and e-mail; their notes;
// what they owe on an open tab (with the Tabs app on: Finance → Tabs settles it); every visit
// (when, where, what it came to, the part on a tab, its state).
import { Mail, Pencil, Phone } from 'lucide-react'
import { useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { perVisit } from './customersLogic'
const ORDER_TONE = { open: 'info', partially_paid: 'warning', paid: 'success', closed: 'neutral', cancelled: 'danger' }
export default function CustomerCard({ customer: c, onClose, onEdit }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const tabsOn = useModule('tabs')
const { data, isPending } = useLiveQuery({
queryKey: ['customer-orders', c.id], queryFn: () => client.get(`/api/customers/${c.id}/orders`).then(r => r.data.orders),
events: ['customers.changed', 'order_closed', 'order_paid'],
})
const { data: tabs = [] } = useLiveQuery({
queryKey: ['customer-tabs', c.id], enabled: tabsOn, queryFn: () => client.get(`/api/tabs/customer/${c.id}`).then(r => r.data),
events: ['tabs.changed'],
})
const openTab = tabs.find(x => x.status === 'open')
const avg = perVisit(c)
return (
<Dialog open size="lg" onClose={onClose} title={c.nickname ? `${c.name} «${c.nickname}»` : c.name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('customers.back')}</Button>
<Button icon={<Pencil size={14} />} onClick={onEdit}>{t('customers.edit')}</Button>
</>}>
<div className="grid gap-4" data-testid="customer-card">
<div className="grid grid-cols-3 gap-2">
{[['visits', fmt.formatNumber(c.visit_count)], ['spent', fmt.formatMoney(c.total_spent)], ['perVisit', avg != null ? fmt.formatMoney(avg) : '—']].map(([k, v]) => (
<div key={k} className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`customers.${k}`)}</span>
<span className="text-body font-semibold tabular-nums text-ink">{v}</span>
</div>
))}
</div>
{openTab && (
<div className="rounded-card border border-danger bg-danger-soft p-3 flex flex-wrap items-center justify-between gap-2" data-testid="customer-tab">
<span className="grid">
<span className="font-semibold text-danger-ink">{t('customers.owes')}</span>
<span className="text-caption text-ink-2">{t('customers.owesSub', { date: fmt.formatDate(openTab.opened_at), paid: fmt.formatMoney(openTab.total_paid) })}</span>
</span>
<span className="text-title font-semibold tabular-nums text-danger-ink">{fmt.formatMoney(openTab.balance)}</span>
</div>
)}
{(c.phone || c.email) && (
<div className="flex flex-wrap gap-4 text-body">
{c.phone && <a href={`tel:${c.phone.replace(/\s/g, '')}`} className="inline-flex items-center gap-1.5 text-accent-ink hover:underline"><Phone size={15} aria-hidden="true" />{c.phone}</a>}
{c.email && <a href={`mailto:${c.email}`} className="inline-flex items-center gap-1.5 text-accent-ink hover:underline"><Mail size={15} aria-hidden="true" />{c.email}</a>}
</div>
)}
{c.notes && <p className="rounded-card bg-warning-soft text-warning-ink p-3 text-label whitespace-pre-wrap">{c.notes}</p>}
<section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('customers.history')}</h3>
{isPending ? <Spinner /> : !data?.length ? <p className="text-label text-ink-3">{t('customers.noVisits')}</p> : (
<ul className="divide-y divide-line">
{data.map(o => (
<li key={o.id} className="py-2 flex flex-wrap items-center gap-2 text-label">
<span className="grid flex-1 min-w-40">
<span className="text-ink font-semibold">
{o.table_name ? t('customers.atTable', { table: o.table_name }) : t(`customers.orderType.${o.order_type}`, { defaultValue: t('customers.noTable') })}
</span>
<span className="text-caption text-ink-3">{fmt.formatDateTime(o.opened_at, 'datetimeShort')} · {t('customers.items', { count: o.item_count })}</span>
</span>
{o.on_tab > 0 && <Pill tone="warning">{t('customers.onTab', { amount: fmt.formatMoney(o.on_tab) })}</Pill>}
<Pill tone={ORDER_TONE[o.status] ?? 'neutral'}>{t(`customers.orderStatus.${o.status}`, { defaultValue: o.status })}</Pill>
<b className="tabular-nums w-20 text-right">{fmt.formatMoney(o.total)}</b>
</li>
))}
</ul>
)}
</section>
</div>
</Dialog>
)
}
@@ -0,0 +1,53 @@
// A new customer or an existing one (plan step 6.13b): name, nickname (how the staff know them),
// phone (caller ID finds them by it), e-mail, notes (allergies, likes). Clearing a field clears it.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { customerBody, customerForm, customerProblems } from './customersLogic'
export default function CustomerDialog({ customer, onClose, onSaved }) {
const { t } = useTranslation('manager')
const isNew = !customer
const [form, setForm] = useState(() => customerForm(customer))
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const wrong = customerProblems(form)
const err = k => (tried && wrong.includes(k) ? t(`customers.wrong.${k}`) : undefined)
const save = useMutation({
mutationFn: body => (isNew ? client.post('/api/customers/', body) : client.put(`/api/customers/${customer.id}`, body)).then(r => r.data),
onSuccess: c => { toast.success(t(isNew ? 'customers.added' : 'customers.saved', { name: c.name })); onSaved(c) },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate(customerBody(form)) }
return (
<Dialog open size="md" onClose={onClose} title={isNew ? t('customers.newTitle') : customer.name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('customers.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="customer-save">{isNew ? t('customers.add') : t('customers.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="customer-dialog">
<Field label={t('customers.name')} required error={err('name')}>
<Input value={form.name} autoFocus onChange={e => set('name', e.target.value)} data-testid="customer-name" />
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('customers.nickname')} hint={t('customers.nicknameHint')}>
<Input value={form.nickname} onChange={e => set('nickname', e.target.value)} />
</Field>
<Field label={t('customers.phone')} hint={t('customers.phoneHint')}>
<Input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} data-testid="customer-phone" />
</Field>
</div>
<Field label={t('customers.email')} error={err('email')}>
<Input type="email" value={form.email} onChange={e => set('email', e.target.value)} />
</Field>
<Field label={t('customers.notes')} hint={t('customers.notesHint')}>
<Textarea rows={3} value={form.notes} onChange={e => set('notes', e.target.value)} data-testid="customer-notes" />
</Field>
</div>
</Dialog>
)
}
@@ -0,0 +1,95 @@
// CRM → Customers (plan step 6.13b; replaces the v1 CustomersPage): the venue's regular
// customers. Search by name, nickname, phone, e-mail or notes (case and Greek accents ignored);
// each with visits, what they spent (counted as in the reports: refunds off, tab lines in) and
// their last visit. A tap opens their card: contact, notes (allergies, likes), their open tab,
// every visit. New, edit, remove (a removed customer stays on old orders). Live: `customers.changed`.
import { useDeferredValue, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Pencil, Plus, Search, Trash2, Users } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Avatar } from '../overview/parts'
import { Panel, Table } from '../reports/kit/parts'
import CustomerCard from './CustomerCard'
import CustomerDialog from './CustomerDialog'
export default function CustomersPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [q, setQ] = useState('')
const search = useDeferredValue(q.trim())
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'card' | 'remove', customer }
const { data, isPending, refetch } = useLiveQuery({
queryKey: ['customers', search], placeholderData: prev => prev,
queryFn: () => client.get('/api/customers/', { params: search ? { search } : {} }).then(r => r.data),
events: ['customers.changed', 'order_closed', 'order_paid'],
})
const rows = data ?? []
const close = () => setDialog(null)
const saved = () => { close(); refetch() }
const remove = useMutation({
mutationFn: c => client.delete(`/api/customers/${c.id}`),
onSuccess: (_r, c) => { toast.success(t('customers.removed', { name: c.name })); saved() },
onError: err => toast.error(errorMessage(err, t)),
})
const stop = fn => ev => { ev.stopPropagation(); fn() }
const columns = [
{ key: 'name', label: t('customers.name'), render: c => (
<span className="flex items-center gap-2">
<Avatar name={c.name} size="sm" />
<span className="grid">
<span className="font-semibold text-ink">{c.name}{c.nickname && <span className="font-normal text-ink-2"> «{c.nickname}»</span>}</span>
{c.notes && <span className="text-caption text-ink-2 line-clamp-1">{c.notes}</span>}
</span>
</span>) },
{ key: 'phone', label: t('customers.phone'), render: c => (c.phone ? <a href={`tel:${c.phone.replace(/\s/g, '')}`} onClick={ev => ev.stopPropagation()} className="text-accent-ink hover:underline">{c.phone}</a> : '') },
{ key: 'visit_count', label: t('customers.visits'), align: 'right' },
{ key: 'total_spent', label: t('customers.spent'), align: 'right', tip: t('customers.spentTip'), render: c => (c.total_spent ? fmt.formatMoney(c.total_spent) : '') },
{ key: 'last_visit', label: t('customers.lastVisit'), sort: c => c.last_visit ?? '', render: c => (c.last_visit ? fmt.formatDate(c.last_visit) : '') },
{ key: 'actions', label: '', sort: false, render: c => (
<span className="flex justify-end gap-0.5">
<IconButton size="sm" variant="ghost" label={t('customers.editOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'edit', customer: c }))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('customers.removeOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'remove', customer: c }))}><Trash2 size={15} /></IconButton>
</span>) },
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="customers-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('customers.title')}</h1>
<p className="text-label text-ink-2">{t('customers.subtitle')}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="customer-new">{t('customers.new')}</Button>
</header>
<div className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('customers.search')} aria-label={t('customers.search')} className="pl-9" data-testid="customer-search" />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !rows.length && !search ? <EmptyState icon={<Users size={28} />} title={t('customers.none')} description={t('customers.noneHint')} />
: (
<Panel padded={false}>
<Table columns={columns} rows={rows} onRow={c => setDialog({ kind: 'card', customer: c })} rowTestId="customer-row"
empty={t('customers.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
</Panel>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <CustomerDialog customer={dialog.customer} onClose={close} onSaved={saved} />}
{dialog?.kind === 'card' && <CustomerCard customer={dialog.customer} onClose={close} onEdit={() => setDialog({ kind: 'edit', customer: dialog.customer })} />}
{dialog?.kind === 'remove' && (
<Dialog open size="sm" onClose={close} title={t('customers.removeTitle', { name: dialog.customer.name })} description={t('customers.removeBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('customers.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.customer)}>{t('customers.removeYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,29 @@
// The rules of CRM → Customers (plan step 6.13b), unit-tested in tests/crm.test.mjs. The backend
// checks the same (routers/customers.py) and does the search (case and Greek accents ignored).
export function customerForm(c) {
return { name: c?.name ?? '', nickname: c?.nickname ?? '', phone: c?.phone ?? '', email: c?.email ?? '', notes: c?.notes ?? '' }
}
export function customerProblems(form) {
const out = []
if (!form.name.trim()) out.push('name')
if (form.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) out.push('email')
return out
}
/** Empty fields are sent as null, so clearing a phone number clears it. */
export function customerBody(form) {
const v = k => form[k].trim() || null
return { name: form.name.trim(), nickname: v('nickname'), phone: v('phone'), email: v('email'), notes: v('notes') }
}
/** Their average per visit, or null. */
export function perVisit(c) {
return c.visit_count > 0 ? Math.round((c.total_spent / c.visit_count) * 100) / 100 : null
}
/** The name with the nickname, as the lists show it. */
export function customerLabel(c) {
return c.nickname ? `${c.name} «${c.nickname}»` : c.name
}
@@ -1,11 +1,14 @@
// Inventory → Stock (plan step 6.13b): not built yet. The page says so, and where the costs and
// throwaways are kept meanwhile. Stock levels need the owner's decisions first (units, counting).
import { Boxes } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { EmptyState } from '@xenia/ui'
export default function StockPage() {
const { t } = useTranslation('manager')
return (
<div className="flex flex-col items-center justify-center h-full text-center gap-3 text-slate-400">
<Boxes size={36} className="opacity-40" />
<p className="text-[15px] font-semibold text-slate-500">Stock Management</p>
<p className="text-[13px]">Coming soon — manage item stock volumes here.</p>
<div className="h-full grid place-items-center p-6" data-testid="stock-page">
<EmptyState icon={<Boxes size={32} />} title={t('stock.title')} description={t('stock.soon')} />
</div>
)
}
@@ -1 +1,163 @@
export { default } from '../WastePage'
// Inventory → Throwaways (plan step 6.13b; replaces the v1 WastePage): log what was thrown away
// (a product, how many, why, a note), with its cost at that moment when the product has a cost,
// in the open business day. Today's entries (deletable today only) and the history of a period:
// totals, by reason, by product, every entry. Live: `waste.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { BarList } from '../reports/kit/charts'
import { PeriodPicker } from '../reports/kit/Period'
import { Panel, Stat, Table } from '../reports/kit/parts'
import { defaultPeriod } from '../reports/kit/reportLogic'
import { REASONS, REASON_TONE, wasteProducts, wasteQuantity, wasteTotals } from './wasteLogic'
const LIVE = ['waste.changed']
export default function ThrowawaysPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [removing, setRemoving] = useState(null)
const { data: day } = useLiveQuery({ queryKey: ['business-day'], queryFn: () => client.get('/api/business-day/current').then(r => r.data), refetchInterval: 60_000 })
const dayId = day?.id ?? null
const today = useLiveQuery({
queryKey: ['waste', 'day', dayId], enabled: !!dayId, events: LIVE,
queryFn: () => client.get('/api/waste/', { params: { business_day_id: dayId } }).then(r => r.data.entries),
})
const params = { ...(period.from ? { date_from: period.from } : {}), ...(period.to ? { date_to: period.to } : {}) }
const history = useLiveQuery({ queryKey: ['waste', 'period', params], events: LIVE, queryFn: () => client.get('/api/waste/', { params }).then(r => r.data.entries) })
const todayRows = today.data ?? []
const rows = history.data ?? []
const totals = wasteTotals(todayRows)
const periodTotals = wasteTotals(rows)
const remove = useMutation({
mutationFn: e => client.delete(`/api/waste/${e.id}`),
onSuccess: () => { toast.success(t('waste.deleted')); setRemoving(null); today.refetch(); history.refetch() },
onError: err => toast.error(errorMessage(err, t)),
})
const reason = r => t(`waste.reasons.${r}`, { defaultValue: r })
const group = (key, label) => Object.values(rows.reduce((m, e) => {
const k = e[key]
m[k] = m[k] ?? { key: k, label: label(e), value: 0, count: 0 }
m[k].value += e.total_cost ?? 0
m[k].count += key === 'reason' ? 1 : e.quantity
return m
}, {})).sort((a, b) => b.value - a.value || b.count - a.count)
const columns = (deletable) => [
{ key: 'logged_at', label: t('waste.when'), render: e => fmt.formatDateTime(e.logged_at, 'datetimeShort') },
{ key: 'product_name', label: t('waste.product'), render: e => <span className="font-semibold text-ink">{e.product_name}</span> },
{ key: 'quantity', label: t('waste.quantity'), align: 'right', render: e => fmt.formatNumber(e.quantity, { maxDecimals: 3 }) },
{ key: 'reason', label: t('waste.reason'), sort: e => reason(e.reason), render: e => (
<span className="grid gap-0.5"><Pill tone={REASON_TONE[e.reason] ?? 'neutral'} className="justify-self-start">{reason(e.reason)}</Pill>
{e.reason_notes && <span className="text-caption text-ink-2">{e.reason_notes}</span>}</span>) },
{ key: 'logged_by_name', label: t('waste.by') },
{ key: 'total_cost', label: t('waste.cost'), align: 'right', render: e => (e.total_cost != null ? fmt.formatMoney(e.total_cost) : <span className="text-ink-3">{t('waste.noCost')}</span>) },
...(deletable ? [{ key: 'del', label: '', sort: false, render: e => (
<IconButton size="sm" variant="ghost" label={t('waste.deleteOf', { name: e.product_name })} onClick={() => setRemoving(e)}><Trash2 size={15} /></IconButton>) }] : []),
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="waste-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header>
<h1 className="text-title font-semibold text-ink">{t('waste.title')}</h1>
<p className="text-label text-ink-2">{t('waste.subtitle')}</p>
</header>
<LogForm onLogged={() => { today.refetch(); history.refetch() }} dayOpen={!!dayId} />
<Panel padded={false} title={t('waste.today')} testId="waste-today"
actions={<span className="text-label text-ink-2">{t('waste.todaySum', { count: totals.count, cost: fmt.formatMoney(totals.cost) })}</span>}>
{!dayId ? <p className="p-4 text-label text-ink-3">{t('waste.noDay')}</p>
: today.isPending ? <div className="p-4"><Spinner /></div>
: <Table columns={columns(true)} rows={todayRows} rowTestId="waste-today-row" empty={t('waste.noneToday')} initialSort={{ key: 'logged_at', dir: 'desc' }} />}
</Panel>
<h2 className="text-body font-semibold text-ink mt-2">{t('waste.history')}</h2>
<PeriodPicker value={period} onChange={setPeriod} allowDay={false} />
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('waste.cost')} tone={periodTotals.cost ? 'danger' : undefined} value={fmt.formatMoney(periodTotals.cost)}
sub={periodTotals.uncosted ? t('waste.uncosted', { count: periodTotals.uncosted }) : undefined} testId="waste-period-cost" />
<Stat label={t('waste.entries')} value={fmt.formatNumber(periodTotals.count)} />
</div>
{rows.length > 0 && (
<div className="grid gap-4 lg:grid-cols-2">
<Panel title={t('waste.byReason')}>
<BarList format={v => fmt.formatMoney(v)} rows={group('reason', e => reason(e.reason)).map(g => ({ ...g, sub: t('waste.times', { count: g.count }) }))} />
</Panel>
<Panel title={t('waste.byProduct')}>
<BarList format={v => fmt.formatMoney(v)} rows={group('product_id', e => e.product_name).slice(0, 10).map(g => ({ ...g, sub: t('waste.units', { qty: fmt.formatNumber(g.count, { maxDecimals: 3 }) }) }))} />
</Panel>
</div>
)}
<Panel padded={false} title={t('waste.every')}>
{history.isPending ? <div className="p-4"><Spinner /></div>
: <Table columns={columns(false)} rows={rows} rowTestId="waste-row" empty={t('waste.noneInPeriod')} initialSort={{ key: 'logged_at', dir: 'desc' }} />}
</Panel>
</div>
{removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t('waste.deleteTitle', { name: removing.product_name })}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('waste.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing)}>{t('waste.deleteYes')}</Button>
</>} />
)}
</div>
)
}
function LogForm({ onLogged, dayOpen }) {
const { t, i18n } = useTranslation('manager')
const fmt = useFormat()
const [form, setForm] = useState({ product_id: '', qty: '1', reason: 'kitchen_error', notes: '' })
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const { data: products = [] } = useLiveQuery({ queryKey: ['products', 'all'], queryFn: () => client.get('/api/products/').then(r => r.data), staleTime: 300_000 })
const qty = wasteQuantity(form.qty)
const log = useMutation({
mutationFn: () => client.post('/api/waste/', { product_id: Number(form.product_id), quantity: qty, reason: form.reason, reason_notes: form.notes.trim() || null }).then(r => r.data),
onSuccess: e => {
toast.success(e.total_cost != null ? t('waste.loggedCost', { name: e.product_name, cost: fmt.formatMoney(e.total_cost) }) : t('waste.logged', { name: e.product_name }))
setForm(f => ({ ...f, product_id: '', qty: '1', notes: '' })); setTried(false); onLogged()
},
onError: err => toast.error(errorMessage(err, t)),
})
const submit = () => { setTried(true); if (form.product_id && qty != null) log.mutate() }
return (
<Panel title={t('waste.log')} testId="waste-form">
<div className="grid gap-3">
<div className="grid gap-3 sm:grid-cols-[2fr_1fr]">
<Field label={t('waste.product')} required error={tried && !form.product_id ? t('waste.pickProduct') : undefined}>
<Select value={form.product_id} onChange={e => set('product_id', e.target.value)} data-testid="waste-product"
options={[{ value: '', label: t('waste.choose') }, ...wasteProducts(products, i18n.language).map(p => ({ value: String(p.id), label: p.name }))]} />
</Field>
<Field label={t('waste.quantity')} required error={tried && qty == null ? t('waste.wrongQty') : undefined}>
<Input inputMode="decimal" value={form.qty} onChange={e => set('qty', e.target.value)} data-testid="waste-qty" />
</Field>
</div>
<Field label={t('waste.reason')}>
<span className="flex flex-wrap gap-1" role="radiogroup" aria-label={t('waste.reason')}>
{REASONS.map(r => (
<Button key={r} size="sm" variant={form.reason === r ? 'primary' : 'secondary'} role="radio" aria-checked={form.reason === r} onClick={() => set('reason', r)}>
{t(`waste.reasons.${r}`)}
</Button>
))}
</span>
</Field>
<Field label={t('waste.note')}>
<Input value={form.notes} onChange={e => set('notes', e.target.value)} placeholder={t('waste.noteHint')} />
</Field>
<div className="flex flex-wrap items-center gap-3">
<Button icon={<Plus size={16} />} loading={log.isPending} onClick={submit} data-testid="waste-log">{t('waste.logIt')}</Button>
{!dayOpen && <span className="text-caption text-ink-3">{t('waste.noDayHint')}</span>}
</div>
</div>
</Panel>
)
}
@@ -0,0 +1,27 @@
// The rules of Inventory → Throwaways (plan step 6.13b), unit-tested in tests/crm.test.mjs.
// As routers/waste.py VALID_REASONS; texts are manager `waste.reasons.*`.
import { parseNumber } from '@xenia/i18n/number' // plain JS: Node tests import this file
export const REASONS = ['kitchen_error', 'dropped', 'expired', 'other']
export const REASON_TONE = { kitchen_error: 'danger', dropped: 'warning', expired: 'accent', other: 'neutral' }
/** A typed quantity (comma or dot) above zero, or null. */
export function wasteQuantity(text) {
const v = parseNumber(String(text ?? ''), { decimals: 3, allowNegative: false })
return v > 0 ? v : null
}
/** Totals of a list of entries: how many, their known cost, how many have no cost. */
export function wasteTotals(entries) {
return {
count: entries.length,
cost: Math.round(entries.reduce((s, e) => s + (e.total_cost ?? 0), 0) * 100) / 100,
uncosted: entries.filter(e => e.total_cost == null).length,
}
}
/** Products for the form: available ones, by name in the language's order. */
export function wasteProducts(products, lang = 'en') {
return products.filter(p => p.is_available !== false && !p.system_key)
.sort((a, b) => a.name.localeCompare(b.name, lang))
}
@@ -0,0 +1,199 @@
// Notes and to-dos (plan step 6.13b; replaces the v1 NotesPage): the managers' shared notes
// (pinned ones first; tap to edit, Ctrl+Enter saves, Esc cancels) and to-dos (urgent first; tick
// when done, who did it is kept; the done ones folded away). The overview's notes card shows the
// same. Live: `notes.changed`.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Check, ChevronDown, Pin, PinOff, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Input, Switch, Textarea, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Panel } from '../reports/kit/parts'
import { splitNotes, splitTodos } from './notesLogic'
const LIVE = ['notes.changed']
function useChange() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
return (fn, done) => ({
mutationFn: fn,
onSuccess: () => { qc.invalidateQueries({ queryKey: ['notes'] }); qc.invalidateQueries({ queryKey: ['todos'] }); if (done) toast.success(done) },
onError: err => toast.error(errorMessage(err, t)),
})
}
export default function NotesPage() {
const { t } = useTranslation('manager')
const { data: notes = [] } = useLiveQuery({ queryKey: ['notes'], queryFn: () => client.get('/api/notes/').then(r => r.data), events: LIVE })
const { data: todos = [] } = useLiveQuery({ queryKey: ['todos'], queryFn: () => client.get('/api/notes/todos').then(r => r.data), events: LIVE })
const [removing, setRemoving] = useState(null) // { kind: 'note' | 'todo', item }
const change = useChange()
const remove = useMutation(change(({ kind, item }) => client.delete(kind === 'note' ? `/api/notes/${item.id}` : `/api/notes/todos/${item.id}`), t('notes.deleted')))
const { pinned, rest } = splitNotes(notes)
const { open, done } = splitTodos(todos)
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="notes-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header>
<h1 className="text-title font-semibold text-ink">{t('notes.title')}</h1>
<p className="text-label text-ink-2">{t('notes.subtitle', { notes: notes.length, todos: open.length })}</p>
</header>
<div className="grid gap-4 lg:grid-cols-2 items-start">
<Panel title={t('notes.notes')} testId="notes-column">
<div className="grid gap-3">
<NewNote />
{pinned.length > 0 && <Label>{t('notes.pinned')}</Label>}
{pinned.map(n => <NoteCard key={n.id} note={n} onDelete={() => setRemoving({ kind: 'note', item: n })} />)}
{pinned.length > 0 && rest.length > 0 && <Label>{t('notes.others')}</Label>}
{rest.map(n => <NoteCard key={n.id} note={n} onDelete={() => setRemoving({ kind: 'note', item: n })} />)}
{!notes.length && <p className="text-label text-ink-3">{t('notes.noNotes')}</p>}
</div>
</Panel>
<Panel title={t('notes.todos')} testId="todos-column">
<div className="grid gap-2">
<NewTodo />
{open.map(x => <TodoRow key={x.id} todo={x} onDelete={() => setRemoving({ kind: 'todo', item: x })} />)}
{!todos.length && <p className="text-label text-ink-3">{t('notes.noTodos')}</p>}
{done.length > 0 && <DoneTodos done={done} onDelete={x => setRemoving({ kind: 'todo', item: x })} />}
</div>
</Panel>
</div>
</div>
{removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t(removing.kind === 'note' ? 'notes.deleteNote' : 'notes.deleteTodo')}
description={removing.item.body.length > 120 ? `${removing.item.body.slice(0, 120)}…` : removing.item.body}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('notes.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing, { onSuccess: () => setRemoving(null) })} data-testid="notes-delete-confirm">{t('notes.deleteYes')}</Button>
</>} />
)}
</div>
)
}
function Label({ children }) {
return <span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{children}</span>
}
function NewNote() {
const { t } = useTranslation('manager')
const [body, setBody] = useState('')
const [pin, setPin] = useState(false)
const change = useChange()
const add = useMutation(change(() => client.post('/api/notes/', { body: body.trim(), is_pinned: pin })))
const submit = () => { if (body.trim()) add.mutate(undefined, { onSuccess: () => { setBody(''); setPin(false) } }) }
return (
<div className="grid gap-2 rounded-card border border-dashed border-line p-3">
<Textarea rows={3} value={body} onChange={e => setBody(e.target.value)} placeholder={t('notes.newNote')} aria-label={t('notes.newNote')}
onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }} data-testid="note-new" />
<div className="flex items-center gap-3">
<Switch checked={pin} onChange={setPin} label={t('notes.pinIt')} />
<span className="flex-1" />
<Button size="sm" icon={<Plus size={14} />} disabled={!body.trim()} loading={add.isPending} onClick={submit} data-testid="note-add">{t('notes.addNote')}</Button>
</div>
</div>
)
}
function NoteCard({ note, onDelete }) {
const { t } = useTranslation('manager')
const { formatDateTime } = useFormat()
const [draft, setDraft] = useState(null)
const change = useChange()
const save = useMutation(change(body => client.put(`/api/notes/${note.id}`, body)))
const finish = () => {
const text = draft?.trim()
if (text && text !== note.body) save.mutate({ body: text })
setDraft(null)
}
return (
<div className={cx('rounded-card border p-3 grid gap-2', note.is_pinned ? 'border-warning bg-warning-soft' : 'border-line bg-surface')} data-testid="note-card">
{draft != null ? (
<Textarea rows={4} autoFocus value={draft} onChange={e => setDraft(e.target.value)} onBlur={finish} aria-label={t('notes.edit')}
onKeyDown={e => { if (e.key === 'Escape') setDraft(null); if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) finish() }} />
) : (
<button type="button" className="text-left text-body text-ink whitespace-pre-wrap break-words" onClick={() => setDraft(note.body)} title={t('notes.tapToEdit')}>{note.body}</button>
)}
<div className="flex items-center gap-2">
<span className="flex-1 text-caption text-ink-3">{note.created_by_name} · {formatDateTime(note.updated_at ?? note.created_at, 'datetimeShort')}</span>
<IconButton size="sm" variant="ghost" label={t(note.is_pinned ? 'notes.unpin' : 'notes.pin')} onClick={() => save.mutate({ is_pinned: !note.is_pinned })}>
{note.is_pinned ? <PinOff size={15} /> : <Pin size={15} />}
</IconButton>
<IconButton size="sm" variant="ghost" label={t('notes.deleteNote')} onClick={onDelete}><Trash2 size={15} /></IconButton>
</div>
</div>
)
}
function NewTodo() {
const { t } = useTranslation('manager')
const [body, setBody] = useState('')
const [urgent, setUrgent] = useState(false)
const change = useChange()
const add = useMutation(change(() => client.post('/api/notes/todos', { body: body.trim(), priority: urgent ? 'high' : 'normal' })))
const submit = () => { if (body.trim()) add.mutate(undefined, { onSuccess: () => { setBody(''); setUrgent(false) } }) }
return (
<div className="grid gap-2 rounded-card border border-dashed border-line p-3">
<Input value={body} onChange={e => setBody(e.target.value)} placeholder={t('notes.newTodo')} aria-label={t('notes.newTodo')}
onKeyDown={e => { if (e.key === 'Enter') submit() }} data-testid="todo-new" />
<div className="flex items-center gap-3">
<Switch checked={urgent} onChange={setUrgent} label={t('notes.urgent')} />
<span className="flex-1" />
<Button size="sm" icon={<Plus size={14} />} disabled={!body.trim()} loading={add.isPending} onClick={submit} data-testid="todo-add">{t('notes.addTodo')}</Button>
</div>
</div>
)
}
function TodoRow({ todo, onDelete }) {
const { t } = useTranslation('manager')
const { formatDateTime } = useFormat()
const [draft, setDraft] = useState(null)
const change = useChange()
const save = useMutation(change(body => client.put(`/api/notes/todos/${todo.id}`, body)))
const finish = () => {
const text = draft?.trim()
if (text && text !== todo.body) save.mutate({ body: text })
setDraft(null)
}
const urgent = todo.priority === 'high' && !todo.is_done
return (
<div className={cx('flex items-start gap-3 rounded-card border p-2.5', urgent ? 'border-danger bg-danger-soft' : 'border-line bg-surface', todo.is_done && 'opacity-70')} data-testid="todo-row">
<button type="button" role="checkbox" aria-checked={todo.is_done} aria-label={t(todo.is_done ? 'notes.undo' : 'notes.markDone', { what: todo.body })}
onClick={() => save.mutate({ is_done: !todo.is_done })} data-testid="todo-done"
className={cx('mt-0.5 w-5 h-5 shrink-0 rounded border-2 grid place-items-center', todo.is_done ? 'bg-success border-success text-success-fg' : urgent ? 'border-danger' : 'border-line')}>
{todo.is_done && <Check size={13} aria-hidden="true" />}
</button>
<span className="flex-1 min-w-0 grid gap-0.5">
{draft != null ? (
<Input autoFocus value={draft} onChange={e => setDraft(e.target.value)} onBlur={finish} aria-label={t('notes.edit')}
onKeyDown={e => { if (e.key === 'Enter') finish(); if (e.key === 'Escape') setDraft(null) }} />
) : (
<button type="button" disabled={todo.is_done} onClick={() => setDraft(todo.body)} className={cx('text-left text-body break-words', todo.is_done ? 'line-through text-ink-3' : 'text-ink')}>
{urgent && <span className="text-caption font-semibold text-danger-ink mr-1.5">{t('notes.urgentTag')}</span>}{todo.body}
</button>
)}
<span className="text-caption text-ink-3">
{todo.created_by_name} · {formatDateTime(todo.created_at, 'datetimeShort')}
{todo.is_done && todo.done_by_name && <span className="text-success-ink"> · {t('notes.doneBy', { name: todo.done_by_name, time: formatDateTime(todo.done_at, 'datetimeShort') })}</span>}
</span>
</span>
<IconButton size="sm" variant="ghost" label={t('notes.deleteTodo')} onClick={onDelete}><Trash2 size={15} /></IconButton>
</div>
)
}
function DoneTodos({ done, onDelete }) {
const { t } = useTranslation('manager')
const [open, setOpen] = useState(false)
return (<>
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} className="flex items-center gap-1 text-label font-semibold text-ink-2 hover:text-ink mt-1" data-testid="todos-done-toggle">
<ChevronDown size={15} className={cx('transition-transform', open && 'rotate-180')} aria-hidden="true" />{t('notes.doneCount', { count: done.length })}
</button>
{open && done.map(x => <TodoRow key={x.id} todo={x} onDelete={() => onDelete(x)} />)}
</>)
}
@@ -0,0 +1,15 @@
// The order of the Notes page (plan step 6.13b), unit-tested in tests/crm.test.mjs.
/** Pinned notes first, then the rest; each newest-edited first. */
export function splitNotes(notes) {
const newest = (a, b) => String(b.updated_at ?? b.created_at).localeCompare(String(a.updated_at ?? a.created_at))
return { pinned: notes.filter(n => n.is_pinned).sort(newest), rest: notes.filter(n => !n.is_pinned).sort(newest) }
}
/** To-dos not done (urgent first, then newest) and done ones (most recently done first). */
export function splitTodos(todos) {
const open = todos.filter(t => !t.is_done).sort((a, b) => (a.priority === 'high' ? 0 : 1) - (b.priority === 'high' ? 0 : 1)
|| String(b.created_at).localeCompare(String(a.created_at)))
const done = todos.filter(t => t.is_done).sort((a, b) => String(b.done_at ?? '').localeCompare(String(a.done_at ?? '')))
return { open, done }
}
@@ -16,8 +16,8 @@ export default function NotesCard() {
const navigate = useNavigate()
const timer = useRef(null)
const [preview, setPreview] = useState(false)
const { data: notes = [] } = useLiveQuery({ queryKey: ['notes'], queryFn: () => client.get('/api/notes/').then(r => r.data), refetchInterval: 60_000 })
const { data: todos = [] } = useLiveQuery({ queryKey: ['todos'], queryFn: () => client.get('/api/notes/todos').then(r => r.data), refetchInterval: 60_000 })
const { data: notes = [] } = useLiveQuery({ queryKey: ['notes'], queryFn: () => client.get('/api/notes/').then(r => r.data), events: ['notes.changed'] })
const { data: todos = [] } = useLiveQuery({ queryKey: ['todos'], queryFn: () => client.get('/api/notes/todos').then(r => r.data), events: ['notes.changed'] })
const items = notesPreview(notes, todos)
const pinned = notes.filter(n => n.is_pinned).length
@@ -11,7 +11,7 @@ import { useNavigate } from 'react-router-dom'
import toast from 'react-hot-toast'
import { BarChart3, Eye, EyeOff, Lock, Play, Power } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useModule } from '@xenia/access'
import { useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
@@ -44,7 +44,8 @@ export default function OverviewPage() {
const navigate = useNavigate()
const qc = useQueryClient()
const license = useContext(LicenseContext)
const notesOn = useModule('notes')
const notesModule = useModule('notes')
const notesOn = useCan('notes.use') && notesModule // what /api/notes checks (6.13b)
const bookingsOn = useModule('reservations')
const chatOn = useModule('chat')
+4 -4
View File
@@ -42,7 +42,7 @@ export const NAV = [
group: 'crm', icon: BookUser, label: 'nav.crm',
children: [
{ to: '/crm/contacts', icon: BookUser, label: 'nav.contacts', module: 'expenses', perm: 'expenses.manage' },
{ to: '/crm/customers', icon: Users, label: 'nav.customers', module: 'crm', perm: DASH },
{ to: '/crm/customers', icon: Users, label: 'nav.customers', module: 'crm', perm: 'crm.manage' },
],
},
{
@@ -70,14 +70,14 @@ export const NAV = [
{ to: '/management/schedule', icon: CalendarDays, label: 'nav.schedule', module: 'staff_planning', perm: 'core.staff.manage' },
{ to: '/management/prep-zones', icon: CookingPot, label: 'nav.prepZones', module: 'catalog', perm: 'catalog.menu.manage' },
{ to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'pricing.manage' },
{ to: '/notes', icon: StickyNote, label: 'nav.notes', module: 'notes', perm: DASH },
{ to: '/notes', icon: StickyNote, label: 'nav.notes', module: 'notes', perm: 'notes.use' },
],
},
{
group: 'inventory', icon: Boxes, label: 'nav.inventory',
children: [
{ to: '/inventory/throwaways', icon: Trash2, label: 'nav.waste', module: 'inventory', perm: DASH },
{ to: '/inventory/stock', icon: Boxes, label: 'nav.stock', module: 'inventory', perm: DASH, placeholder: true },
{ to: '/inventory/throwaways', icon: Trash2, label: 'nav.waste', module: 'inventory', perm: 'inventory.manage' },
{ to: '/inventory/stock', icon: Boxes, label: 'nav.stock', module: 'inventory', perm: 'inventory.manage', placeholder: true },
],
},
],
+37
View File
@@ -0,0 +1,37 @@
// Customers, throwaways and notes as plain data (plan step 6.13b).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { customerBody, customerForm, customerLabel, customerProblems, perVisit } from '../src/pages/customers/customersLogic.js'
import { wasteProducts, wasteQuantity, wasteTotals } from '../src/pages/inventory/wasteLogic.js'
import { splitNotes, splitTodos } from '../src/pages/notes/notesLogic.js'
test('a customer: a name needed, a wrong e-mail caught, empty fields cleared', () => {
const f = customerForm(null)
assert.deepEqual(customerProblems(f), ['name'])
assert.deepEqual(customerProblems({ ...f, name: 'Γιώργος', email: 'x@' }), ['email'])
assert.deepEqual(customerBody({ ...f, name: ' Γιώργος ', nickname: ' ', phone: '697' }), { name: 'Γιώργος', nickname: null, phone: '697', email: null, notes: null })
assert.equal(customerLabel({ name: 'Kostas', nickname: 'Big K' }), 'Kostas «Big K»')
assert.equal(perVisit({ visit_count: 3, total_spent: 50 }), 16.67)
assert.equal(perVisit({ visit_count: 0, total_spent: 0 }), null)
})
test('throwaways: quantities with a comma, totals, the products offered', () => {
assert.equal(wasteQuantity('1,5'), 1.5)
assert.equal(wasteQuantity('0'), null)
assert.equal(wasteQuantity('x'), null)
assert.deepEqual(wasteTotals([{ total_cost: 2.5 }, { total_cost: null }, { total_cost: 1.25 }]), { count: 3, cost: 3.75, uncosted: 1 })
const products = [{ name: 'Σουβλάκι' }, { name: 'Απλή πίτα' }, { name: 'Off', is_available: false }, { name: 'Delivery', system_key: 'delivery_fee' }]
assert.deepEqual(wasteProducts(products, 'el').map(p => p.name), ['Απλή πίτα', 'Σουβλάκι'])
})
test('notes: pinned first; to-dos: urgent first, done apart', () => {
const { pinned, rest } = splitNotes([
{ id: 1, is_pinned: false, updated_at: '2026-11-19T10:00:00Z' }, { id: 2, is_pinned: true, updated_at: '2026-11-18T10:00:00Z' },
{ id: 3, is_pinned: false, updated_at: '2026-11-19T11:00:00Z' }])
assert.deepEqual([pinned.map(n => n.id), rest.map(n => n.id)], [[2], [3, 1]])
const { open, done } = splitTodos([
{ id: 1, is_done: false, priority: 'normal', created_at: '2026-11-19T12:00:00Z' },
{ id: 2, is_done: false, priority: 'high', created_at: '2026-11-18T12:00:00Z' },
{ id: 3, is_done: true, priority: 'high', done_at: '2026-11-19T09:00:00Z' }])
assert.deepEqual([open.map(t => t.id), done.map(t => t.id)], [[2, 1], [3]])
})
+2 -2
View File
@@ -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/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"
],
"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/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"
]
}