Files
bellsystems-cp/frontend/src/modals/bellcloud/devices/EditBacklightModal.jsx
T
bonaminandClaude Opus 5.5 62be80c9d8 fix(devices): write devices in Firestore schema v1 so the apps can read them
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>
2026-11-08 20:00:33 +02:00

163 lines
5.4 KiB
React

// frontend/src/modals/devices/EditBacklightModal.jsx
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')}`
}
return ''
}
function timeToIso(hhmm) {
if (!hhmm) return null
return `2000-01-01T${hhmm}:00Z`
}
const toBool = (v) => v === 'true' || v === true
export default function EditBacklightModal({ open, onClose, onSaved, attr, clock, sub, id, sendMqttCommand }) {
const maxOutputs = sub?.maxOutputs || 8
const bellOutputsUsed = (attr?.bellOutputs || []).filter((o) => o > 0)
const clockOutputsUsed = (clock?.clockOutputs || []).filter((o) => o > 0)
const [isOn, setIsOn] = useState(String(clock?.isBacklightAutomationOn ?? false))
const [output, setOutput] = useState(String(clock?.backlightOutput ?? 0))
const [onTime, setOnTime] = useState(extractTime(clock?.backlightTurnOnTime))
const [offTime, setOffTime] = useState(extractTime(clock?.backlightTurnOffTime))
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const validationMsg = (() => {
if (!toBool(isOn)) return null
if (!output || output === '0') return 'An output must be assigned when backlight automation is enabled.'
if (!onTime || !offTime) return 'Both Turn On and Turn Off times must be set.'
return null
})()
const handleSave = async () => {
if (validationMsg) return
setSaving(true)
setError('')
try {
const enabled = toBool(isOn)
// Push to the device first — only write Firestore once it confirms.
await sendMqttCommand('clock.set_backlight', {
backlight: enabled,
backlight_output: Number(output),
backlight_on: enabled ? onTime : undefined,
backlight_off: enabled ? offTime : undefined,
})
await api.put(`/devices/${id}`, {
device_attributes: {
clockSettings: {
...clock,
isBacklightAutomationOn: enabled,
backlightOutput: Number(output),
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : 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)
}
}
return (
<Modal
open={open}
onClose={onClose}
title="Edit Backlight Settings"
size="sm"
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}>
Sync & Save Settings
</Button>
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
{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>
)}
<FormField
label="Automation"
name="isOn"
type="select"
value={isOn}
onChange={(e) => setIsOn(e.target.value)}
>
<option value="true">Automated</option>
<option value="false">Disabled</option>
</FormField>
<FormField
label="Output"
name="output"
type="select"
value={output}
onChange={(e) => setOutput(e.target.value)}
>
<option value="0">Disabled</option>
{Array.from({ length: maxOutputs }, (_, j) => {
const out = j + 1
const isBell = bellOutputsUsed.includes(out)
const isClock = clockOutputsUsed.includes(out)
return (
<option key={out} value={String(out)}>
Output {out}{isBell ? ' (Bell)' : isClock ? ' (Clock)' : ''}
</option>
)
})}
</FormField>
{toBool(isOn) && (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
<FormField
label="Turn On Time"
name="onTime"
value={onTime}
onChange={(e) => setOnTime(e.target.value)}
placeholder="HH:MM"
/>
<FormField
label="Turn Off Time"
name="offTime"
value={offTime}
onChange={(e) => setOffTime(e.target.value)}
placeholder="HH:MM"
/>
</div>
)}
{error && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
)}
</div>
</Modal>
)
}