// frontend/src/modals/bellcloud/devices/EditAlertsModal.jsx // Edits: alert type (segmented), tempo, bell assignments, day/night silence. import { useState } from 'react' import Modal from '@/components/ui/Modal' import Button from '@/components/ui/Button' import FormField from '@/components/ui/FormField' import api from '@/lib/api' function extractTime(tsStr) { if (!tsStr) return '' const d = new Date( tsStr.replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC') ) if (!isNaN(d.getTime())) { return `${d.getUTCHours().toString().padStart(2, '0')}:${d.getUTCMinutes().toString().padStart(2, '0')}` } const match = tsStr.match(/(\d{1,2}):(\d{2})/) return match ? `${match[1].padStart(2, '0')}:${match[2]}` : '' } function timeToIso(hhmm) { if (!hhmm) return null return `2000-01-01T${hhmm}:00Z` } const TEMPO_OPTIONS = [500, 1000, 1500, 2000, 2500] function msLabel(ms) { return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${ms}ms` } // Segmented button group for alert type function AlertTypeSelector({ value, onChange }) { const options = [ { value: 'disabled', label: 'Disabled' }, { value: 'single', label: 'Single Fire' }, { value: 'multi', label: 'Hour Indicating' }, ] return (
{options.map((opt, i) => ( ))}
) } // Inline on/off toggle row for silence periods function SilenceBlock({ title, isOn, onToggle, from, onFromChange, to, onToChange }) { return (
{title}
{isOn && (
onFromChange(e.target.value)} placeholder="HH:MM" /> onToChange(e.target.value)} placeholder="HH:MM" />
)}
) } // Console UI uses alertType 'disabled'|'single'|'multi'; firmware uses // alert_type 'OFF'|'SINGLE'|'HOURS'. Bell fields: console uses 0 = disabled, // firmware uses 255 = disabled. const ALERT_TYPE_TO_FIRMWARE = { disabled: 'OFF', single: 'SINGLE', multi: 'HOURS' } const toFirmwareBell = (n) => (n === 0 ? 255 : n) export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, id, sendMqttCommand }) { // Only bells that actually have a relay output assigned — same source of // truth as BellsTab's bell cards. Ignores attr.totalBells, which can drift // from the real configured count. 0 and 65535 both mean "no output assigned" // on the wire (uint16 "unset" sentinel) — treat both as disconnected here too, // in case older Firestore data still has 65535 values from before that was // normalized on write. const connectedBellIndexes = (attr?.bellOutputs || []) .map((output, i) => ({ output, bellNumber: i + 1 })) .filter(({ output }) => output > 0 && output !== 65535) .map(({ bellNumber }) => bellNumber) const [alertType, setAlertType] = useState(clock?.ringAlerts || 'disabled') const [ringIntervals, setRingIntervals] = useState(clock?.ringIntervals ?? 1000) const [hourBell, setHourBell] = useState(String(clock?.hourAlertsBell ?? 0)) const [halfBell, setHalfBell] = useState(String(clock?.halfhourAlertsBell ?? 0)) const [quarterBell, setQuarterBell] = useState(String(clock?.quarterAlertsBell ?? 0)) const [isDayOn, setIsDayOn] = useState(clock?.isDaySilenceOn ?? false) const [daySilenceFrom, setDaySilenceFrom] = useState(extractTime(clock?.daySilenceFrom)) const [daySilenceTo, setDaySilenceTo] = useState(extractTime(clock?.daySilenceTo)) const [isNightOn, setIsNightOn] = useState(clock?.isNightSilenceOn ?? false) const [nightFrom, setNightFrom] = useState(extractTime(clock?.nightSilenceFrom)) const [nightTo, setNightTo] = useState(extractTime(clock?.nightSilenceTo)) const [saving, setSaving] = useState(false) const [error, setError] = useState('') const validationMsg = (() => { if (alertType === 'multi' && !ringIntervals) return 'Alert Tempo must be set for Hour Indicating mode.' if (isDayOn && (!daySilenceFrom || !daySilenceTo)) return 'Day Silence is on — set both From and Until times.' if (isNightOn && (!nightFrom || !nightTo)) return 'Night Silence is on — set both From and Until times.' return null })() const handleSave = async () => { if (validationMsg) return setSaving(true) setError('') try { // Push to the device first — clock.set_alerts_config batches alert type/bells // and both silence windows into one round trip. Firestore is only written // once the device confirms. await sendMqttCommand('clock.set_alerts_config', { alert_type: ALERT_TYPE_TO_FIRMWARE[alertType], alert_interval: alertType === 'multi' ? ringIntervals : undefined, hour_bell: toFirmwareBell(Number(hourBell)), half_bell: toFirmwareBell(Number(halfBell)), quarter_bell: toFirmwareBell(Number(quarterBell)), daytime_silence: isDayOn, daytime_on: isDayOn ? daySilenceFrom : undefined, daytime_off: isDayOn ? daySilenceTo : undefined, night_silence: isNightOn, night_on: isNightOn ? nightFrom : undefined, night_off: isNightOn ? nightTo : undefined, }) await api.put(`/devices/${id}`, { device_attributes: { clockSettings: { ...clock, ringAlerts: alertType, ringIntervals: alertType === 'multi' ? ringIntervals : clock?.ringIntervals, hourAlertsBell: Number(hourBell), halfhourAlertsBell: Number(halfBell), quarterAlertsBell: Number(quarterBell), isDaySilenceOn: isDayOn, daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom ?? null), daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo ?? null), isNightSilenceOn: isNightOn, nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom ?? null), nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo ?? null), }, }, }) await onSaved() onClose() } catch (err) { // sendMqttCommand already surfaced a failure toast if the device rejected it. setError(err.message || 'Failed to save.') } finally { setSaving(false) } } const bellOptions = [ { value: '0', label: 'Disabled' }, ...connectedBellIndexes.map((n) => ({ value: String(n), label: `Bell ${n}` })), ] return ( } >
{/* Alert type segmented selector */}
Alert Type
{/* Tempo — only for Hour Indicating */} {alertType === 'multi' && (
Alert Tempo {msLabel(ringIntervals)}
= 0 ? TEMPO_OPTIONS.indexOf(ringIntervals) : 1} onChange={e => setRingIntervals(TEMPO_OPTIONS[Number(e.target.value)])} style={{ width: '100%', accentColor: 'var(--color-primary)', cursor: 'pointer' }} />
{msLabel(TEMPO_OPTIONS[0])} {msLabel(TEMPO_OPTIONS[TEMPO_OPTIONS.length - 1])}
)}
{/* Bell assignments */}
setHourBell(e.target.value)}> {bellOptions.map(o => )} setHalfBell(e.target.value)}> {bellOptions.map(o => )} setQuarterBell(e.target.value)}> {bellOptions.map(o => )}
{/* Silence periods */} setIsDayOn(v => !v)} from={daySilenceFrom} onFromChange={setDaySilenceFrom} to={daySilenceTo} onToChange={setDaySilenceTo} /> setIsNightOn(v => !v)} from={nightFrom} onFromChange={setNightFrom} to={nightTo} onToChange={setNightTo} /> {/* Warnings / errors */} {validationMsg && (

{validationMsg}

)} {error && (

{error}

)}
) }