// Messages to the staff's phones (plan step 6.2): the latest ones with who they went to and how
// many have read them; "New" writes one to everyone or to chosen waiters, optionally about some
// tables, from a quick template or typed. The shift list's message button opens the same
// dialog with that waiter chosen.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { MessageSquare, Plus, Send } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { messageAcks, messageTargets, tableName } from './overviewLogic'
import { Card, Pill } from './parts'
const useTemplates = () => useLiveQuery({
queryKey: ['quick-templates'], queryFn: () => client.get('/api/notifications/templates').then(r => r.data), staleTime: 60_000,
})
export default function MessagesCard({ staff, tables }) {
const { t } = useTranslation('manager')
const { formatTime } = useFormat()
const [composing, setComposing] = useState(false)
const { data: messages = [] } = useLiveQuery({
queryKey: ['messages-all'],
queryFn: () => client.get('/api/notifications/all', { params: { limit: 20 } }).then(r => r.data),
events: ['message_sent'],
refetchInterval: 30_000, // reads (acks) send no event
})
return (
} onClick={() => setComposing(true)} data-testid="message-new">{t('overview.messages.new')}}>
{messages.length === 0 ? } title={t('overview.messages.none')} /> : (
{messages.map(m => {
const to = messageTargets(m, staff)
const acks = messageAcks(m, staff.length)
return (
-
{m.body}
{t('overview.messages.to', { who: to ? to.join(', ') : t('overview.messages.everyone'), time: formatTime(m.created_at) })}
{t('overview.messages.read', { read: acks.read, of: acks.of })}
)
})}
)}
{composing && setComposing(false)} />}
)
}
/** Write a message; `to` preselects one waiter ({ id, name }) and hides the pickers. */
export function ComposeDialog({ staff = [], tables = [], to, onClose }) {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const { data: templates = [] } = useTemplates()
const [waiters, setWaiters] = useState(to ? [to.id] : []) // [] = everyone
const [tableIds, setTableIds] = useState([])
const [body, setBody] = useState('')
const send = useMutation({
mutationFn: payload => client.post('/api/notifications/send', payload),
onSuccess: () => { toast.success(t('overview.messages.sent')); qc.invalidateQueries({ queryKey: ['messages-all'] }); onClose() },
onError: err => toast.error(errorMessage(err, t)),
})
const toggle = (list, set, id) => set(list.includes(id) ? list.filter(x => x !== id) : [...list, id])
const chip = on => (on ? 'primary' : 'secondary')
return (
)
}