The FlutterFlow tablet and phone apps parse each device doc inside safeGet: one wrongly typed field makes them silently drop the whole device from the user's list. The console was the source of every such field found in production on 2026-11-08: - New devices: DeviceCreate defaulted times to "" and IPs to [], and create_device wrote them as-is. Every console-created device was invisible in the apps from birth. It also set device_id but not serial_number. - Round trip: reads formatted Timestamps as "15 January 2026 at 22:01:00 UTC+0000", the frontend echoed that back on save, and _restore_timestamps could not parse it (nor ""), so it stored the string. towerClockTime was not in its list at all. - Key spelling: the console wrote bellGuardSafetyOn / useStaticIP; the apps read bellguardSafetyOn / usesStaticIP, so console edits never reached them and docs ended up with both spellings disagreeing. - MelodyMainItem used the melodies-collection shape (information, url, ...) instead of the device shape the apps read (mainInformation, binaryUrl, ...); Pydantic dropped every real key on read. - Manufacturing batches created devices with serial_number but no device_id, which both apps use to connect over MQTT (7 of 14 devices affected). The contract now lives in the bellsystems-schema repo (v1 = what the shipped apps read). backend/devices/firestore_v1.py enforces it on every device write (to_firestore) and read (to_api): - Timestamps: ISO 8601 in the API, Firestore Timestamps in the DB, null for unset. The old display format is still accepted on write so an open browser tab can't corrupt data; anything unparseable is a 422. - IPs: dotted strings; octet arrays are joined; invalid values are a 422. - Legacy keys are renamed (v1 key wins over a duplicate); users_list dropped. - device_id mirrors serial_number (decision D1); conflicting values are a 422. - user_list / melodyReference entries become DocumentReferences. - update_device re-normalizes the merged nested maps, so saving a device also repairs pre-v1 junk already stored in it. Models and the frontend now use v1 names and send null (not "") for unset times. The firmware's network.set_config MQTT payload keeps its own names. Verified: 114 backend tests pass (new tests/test_firestore_v1.py covers the production failure shapes; test_timezones.py not run locally, needs tzdata). A read-only dry run of a console save against all 14 production devices produced v1-valid docs with no fields lost. Frontend builds. Not deployed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
311 lines
14 KiB
React
311 lines
14 KiB
React
// 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 (
|
|
<div style={{ display: 'flex', gap: 0, borderRadius: 'var(--radius-md)', overflow: 'hidden', border: '1px solid var(--color-border)' }}>
|
|
{options.map((opt, i) => (
|
|
<button
|
|
key={opt.value}
|
|
type="button"
|
|
onClick={() => onChange(opt.value)}
|
|
style={{
|
|
flex: 1,
|
|
padding: 'var(--space-2) var(--space-3)',
|
|
fontSize: 'var(--font-size-sm)',
|
|
fontWeight: value === opt.value ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
|
|
color: value === opt.value ? 'var(--color-text-inverse)' : 'var(--color-text-muted)',
|
|
backgroundColor: value === opt.value ? 'var(--color-primary-container)' : 'var(--color-bg-elevated)',
|
|
border: 'none',
|
|
borderLeft: i > 0 ? '1px solid var(--color-border)' : 'none',
|
|
cursor: 'pointer',
|
|
transition: 'background-color 0.15s, color 0.15s',
|
|
}}
|
|
>
|
|
{opt.label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// Inline on/off toggle row for silence periods
|
|
function SilenceBlock({ title, isOn, onToggle, from, onFromChange, to, onToChange }) {
|
|
return (
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
|
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
|
<span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
|
{title}
|
|
</span>
|
|
<button
|
|
type="button"
|
|
role="switch"
|
|
aria-checked={isOn}
|
|
onClick={onToggle}
|
|
style={{
|
|
position: 'relative',
|
|
width: 36,
|
|
height: 20,
|
|
borderRadius: 'var(--radius-full)',
|
|
backgroundColor: isOn ? 'var(--color-primary-container)' : 'var(--color-bg-island)',
|
|
border: `1px solid ${isOn ? 'var(--color-primary)' : 'var(--color-border-strong)'}`,
|
|
cursor: 'pointer',
|
|
padding: 0,
|
|
transition: 'background-color 0.2s, border-color 0.2s',
|
|
flexShrink: 0,
|
|
}}
|
|
>
|
|
<div style={{
|
|
position: 'absolute',
|
|
top: 2,
|
|
left: isOn ? 17 : 2,
|
|
width: 14,
|
|
height: 14,
|
|
borderRadius: 'var(--radius-full)',
|
|
backgroundColor: isOn ? 'var(--color-primary)' : 'var(--color-text-muted)',
|
|
transition: 'left 0.2s',
|
|
}} />
|
|
</button>
|
|
</div>
|
|
{isOn && (
|
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
|
<FormField label="From" name={`${title}-from`} value={from} onChange={e => onFromChange(e.target.value)} placeholder="HH:MM" />
|
|
<FormField label="Until" name={`${title}-to`} value={to} onChange={e => onToChange(e.target.value)} placeholder="HH:MM" />
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// 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 (
|
|
<Modal
|
|
open={open}
|
|
onClose={onClose}
|
|
title="Alert Settings"
|
|
size="md"
|
|
footer={
|
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
|
<Button variant="ghost" onClick={onClose}>Cancel</Button>
|
|
<Button variant="primary" loading={saving} disabled={!!validationMsg} onClick={handleSave}>
|
|
Save Settings
|
|
</Button>
|
|
</div>
|
|
}
|
|
>
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
|
|
|
{/* Alert type segmented selector */}
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
|
|
Alert Type
|
|
</span>
|
|
<AlertTypeSelector value={alertType} onChange={setAlertType} />
|
|
</div>
|
|
|
|
{/* Tempo — only for Hour Indicating */}
|
|
{alertType === 'multi' && (
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
|
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
|
|
Alert Tempo
|
|
</span>
|
|
<span style={{ fontFamily: 'var(--font-family-display)', fontSize: 'var(--font-size-lg)', fontWeight: 'var(--font-weight-bold)', color: 'var(--color-primary)', letterSpacing: 'var(--tracking-tight)' }}>
|
|
{msLabel(ringIntervals)}
|
|
</span>
|
|
</div>
|
|
<input
|
|
type="range"
|
|
min={0}
|
|
max={TEMPO_OPTIONS.length - 1}
|
|
step={1}
|
|
value={TEMPO_OPTIONS.indexOf(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' }}
|
|
/>
|
|
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{msLabel(TEMPO_OPTIONS[0])}</span>
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{msLabel(TEMPO_OPTIONS[TEMPO_OPTIONS.length - 1])}</span>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
|
|
|
|
{/* Bell assignments */}
|
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 'var(--space-3)' }}>
|
|
<FormField label="Hours Bell" name="hourBell" type="select" value={hourBell} onChange={e => setHourBell(e.target.value)}>
|
|
{bellOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
|
</FormField>
|
|
<FormField label="Half-Hours Bell" name="halfBell" type="select" value={halfBell} onChange={e => setHalfBell(e.target.value)}>
|
|
{bellOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
|
</FormField>
|
|
<FormField label="Quarters Bell" name="quarterBell" type="select" value={quarterBell} onChange={e => setQuarterBell(e.target.value)}>
|
|
{bellOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
|
</FormField>
|
|
</div>
|
|
|
|
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
|
|
|
|
{/* Silence periods */}
|
|
<SilenceBlock
|
|
title="Day Silence"
|
|
isOn={isDayOn}
|
|
onToggle={() => setIsDayOn(v => !v)}
|
|
from={daySilenceFrom}
|
|
onFromChange={setDaySilenceFrom}
|
|
to={daySilenceTo}
|
|
onToChange={setDaySilenceTo}
|
|
/>
|
|
<SilenceBlock
|
|
title="Night Silence"
|
|
isOn={isNightOn}
|
|
onToggle={() => setIsNightOn(v => !v)}
|
|
from={nightFrom}
|
|
onFromChange={setNightFrom}
|
|
to={nightTo}
|
|
onToChange={setNightTo}
|
|
/>
|
|
|
|
{/* Warnings / errors */}
|
|
{validationMsg && (
|
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
|
{validationMsg}
|
|
</p>
|
|
)}
|
|
{error && (
|
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
|
|
)}
|
|
</div>
|
|
</Modal>
|
|
)
|
|
}
|