-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtypes.ts
More file actions
4063 lines (3704 loc) Β· 114 KB
/
Copy pathtypes.ts
File metadata and controls
4063 lines (3704 loc) Β· 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module api/types
*
* Every exported interface and type alias used across the API layer.
*
* === SI Unit Conventions ===
*
* Field names carry their unit as a suffix. Fields marked `(SI)` are stored
* and transported in canonical SI (or derived-SI) form; the frontend
* unit-conversion layer (`@/lib/unitConversion`) is the only place that
* converts to user-display units.
*
* `_m` -> meters (SI: length)
* `_km` -> kilometers (derived SI)
* `_c` -> degrees Celsius (SI: temperature)
* `_pa` -> pascals (SI: pressure)
* `_kg` -> kilograms (SI: mass)
* `_kwh` -> kilowatt-hours (derived SI: energy)
* `_kw` -> kilowatts (derived SI: power)
* `_wh_km` -> watt-hours per kilometer (derived SI: energy intensity)
* `_v` /
* `_voltage` -> volts (derived SI: electric potential)
* `_amps` -> amperes (SI: electric current)
* `_nm` -> newton-meters (derived SI: torque)
* `_rpm` -> revolutions per minute (NON-SI; angular velocity)
* `_sec` -> seconds (SI: time)
* `_ms` -> milliseconds (derived SI: time)
*
* NON-SI suffixes (legacy / display-only): `_mi`, `_mph`, `_psi`, `_f`,
* `_min`, `_hr`. These mirror Go struct fields in source units; the API
* does NOT convert them β `lib/unitConversion.ts` does on the boundary.
*
* Rule of thumb: any field tagged `(SI)` in JSDoc below is safe to feed
* directly into `metersToKm()` / `celsiusToF()` / `pascalsToPsi()` etc.
*
* Mirrors Go structs under `internal/api/*`, `internal/models/*`, and
* `internal/tesla/protomodel/*`.
*/
import type {
Automation as AutomationModel,
AutomationActionInput,
AutomationConditionInput,
AutomationTriggerInput,
} from '@/types/automations'
// === Core Types ===
export interface Vehicle {
id: number
vehicle_id: number
vin: string
display_name: string
model: string
trim_badging: string
exterior_color: string
wheel_type: string
state: string
healthy: boolean
/** IANA tz database name reported by Tesla (e.g. "America/Los_Angeles"). 'UTC' = unknown β frontend falls back to user TZ. */
timezone?: string
created_at: string
updated_at: string
}
/** JSON values returned by Tesla-controlled, undocumented Fleet API schemas. */
export type TeslaJSONValue =
| string
| number
| boolean
| null
| TeslaJSONValue[]
| TeslaOpaqueObject
/** Opaque Tesla-controlled JSON object for undocumented request schemas. */
export type TeslaOpaqueObject = { [key: string]: TeslaJSONValue }
/** Cached vehicle-management response stored in tesla_user_config. */
export interface VehicleInfoEnvelope<T = TeslaOpaqueObject> {
data: T | null
fetched_at: string | null
}
/** Non-persisted response from an opaque Vehicle Management mutation. */
export interface VehicleManagementResult {
data: TeslaJSONValue
}
export interface VehiclePricingVariables {
payload: TeslaOpaqueObject
}
export interface EnterprisePayerVariables {
payload: TeslaOpaqueObject
confirmed: boolean
}
// VehicleLiveState removed β vehicle_live_state table dropped.
// Use VehicleState (from /vehicles/{id}/state via SignalStore) or
// VehicleLiveState from hooks/useVehicleLive (SSE) instead.
// Position mirrors the typed `positions` hypertable.
// High-frequency GPS + motion sample.
// Typed-only β no raw_json / JSONB carve-outs (ADR-001, ADR-005).
// Matches Go model in internal/models/position.go.
export interface Position {
vehicle_id: number
ts: string
latitude: number
longitude: number
heading: number | null
speed_mph: number | null
/** Elevation in meters (SI). */
elevation_m: number | null
gps_state: string | null
source: string
}
export interface Drive {
id: number
vehicle_id: number
start_ts: string
end_ts: string | null
/** Drive duration in seconds (SI canonical). */
duration_s: number
/** Distance travelled in meters (SI canonical). */
distance_m: number
start_address: string | null
end_address: string | null
start_lat: number | null
start_lon: number | null
end_lat: number | null
end_lon: number | null
start_soc_pct: number
end_soc_pct: number | null
/** Energy used in watt-hours (Wh, SI canonical). */
energy_used_wh: number | null
/** Energy recovered via regen in watt-hours (Wh, SI canonical). */
regen_energy_wh: number | null
/** Average speed in meters per second (SI canonical). */
avg_speed_mps: number | null
/** Maximum speed in meters per second (SI canonical). */
max_speed_mps: number | null
/** Average power in watts (W, SI canonical). */
avg_power_w: number | null
/** Average ambient temperature in degrees Celsius (SI). */
outside_temp_avg_c: number | null
/** Average inside cabin temperature in degrees Celsius (SI; nullable, column dropped). */
inside_temp_avg_c: number | null
score: number | null
ended_status: string | null
created_at: string
updated_at: string
}
export interface ChargingSession {
id: number
vehicle_id: number
started_at: string
ended_at: string | null
start_soc_pct: number
end_soc_pct: number | null
delta_soc_pct: number | null
start_odometer_m: number | null
end_odometer_m: number | null
start_lat: number | null
start_lng: number | null
start_place: string | null
/** Energy added in watt-hours (Wh, SI canonical). */
total_energy_added_wh: number
/** Peak charger power in watts (W, SI canonical). */
peak_power_w: number | null
/** Average charger power in watts (W, SI canonical). */
avg_power_w: number | null
cost_decimal: number | null
cost_currency: string | null
charger_type: string | null
cable_type: string | null
live?: boolean
start_ts?: string
end_ts?: string | null
startedAt: string
duration_min: number
cost?: number | null
ended_status?: string | null
/** Supercharger invoice energy in watt-hours when Tesla billing history matches. */
billed_energy_wh?: number | null
/** Supercharger invoice total when Tesla billing history matches. */
billed_cost_decimal?: number | null
billed_currency?: string | null
billed_rate_per_kwh?: number | null
billed_source?: string | null
billed_site?: string | null
billed_fee_type?: string | null
}
export interface DriveTelemetryReading {
id: number
drive_id: number
vehicle_id: number
latitude: number | null
longitude: number | null
elevation: number | null
heading: number | null
odometer: number | null
speed: number | null
power: number | null
battery_level: number | null
soc: number | null
usable_soc: number | null
rated_range: number | null
ideal_range: number | null
est_range: number | null
inside_temp: number | null
outside_temp: number | null
driver_temp: number | null
passenger_temp: number | null
fan_status: number | null
is_climate_on: boolean | null
tire_pressure_fl: number | null
tire_pressure_fr: number | null
tire_pressure_rl: number | null
tire_pressure_rr: number | null
battery_heater_on: boolean | null
created_at: string
}
export interface ChargeTelemetryReading {
session_id: number | null
vehicle_id: number
ts: string
ac_charging_power_w: number | null
dc_charging_power_w: number | null
ac_charging_energy_in_wh: number | null
dc_charging_energy_in_wh: number | null
charger_voltage_v: number | null
charger_actual_current_a: number | null
charger_pilot_current_a: number | null
charger_phases: number | null
battery_heater_on: boolean | null
battery_heater_power_w: number | null
charge_limit_soc_pct: number | null
charge_request: string | null
fast_charger_type: string | null
charging_cable_type: string | null
charge_port_door_open: boolean | null
charge_port_latch: string | null
created_at: string
battery_level?: number | null
soc?: number | null
power_kw?: number | null
energy_added?: number | null
rated_range?: number | null
battery_temp?: number | null
inside_temp?: number | null
outside_temp?: number | null
voltage?: number | null
current_amps?: number | null
}
// === Geofences / Charging Places ===
//
// Canonical snake_case wire shape for GET/POST/PUT /geofences and the
// charging-place pricing feature's endpoints beneath
// /geofences/{geofenceID}/... (see internal/api/geofence/rate_handler.go
// and internal/models/system/{system,geofence_rate}.go β the source of
// truth for every field below).
//
// `rate_per_wh` is the ONLY canonical electricity-rate unit on the wire β
// never `_kwh`. Convert to currency/kWh strictly at the render/request
// boundary (see features/maps/components/charging-places/helpers.ts).
/** How a geofence came to exist. */
export type GeofenceOrigin = 'manual' | 'charging_discovery'
/** Optional category tag a geofence may carry. */
export type GeofenceCategory = 'home' | 'work' | 'restricted' | 'custom'
/**
* A geofence ("charging place" once it has rates/sessions attached).
*
* `latitude` / `longitude` / `radius` are NOT stored columns β the backend's
* `Geofence.MarshalJSON` derives them on every read from `polygon_wkt`
* (centroid + max-vertex-distance in meters) so the web client never parses
* WKT itself. `category` / `archived_at` use `omitempty` on the Go side:
* they are ABSENT from the payload (not `null`) when unset.
*/
export interface Geofence {
id: number
name: string
polygon_wkt: string
category?: GeofenceCategory | null
enabled: boolean
alert_on_entry: boolean
alert_on_exit: boolean
origin: GeofenceOrigin
needs_review: boolean
archived_at?: string | null
created_at: string
updated_at: string
/** Computed centroid latitude, degrees β see MarshalJSON note above. */
latitude: number
/** Computed centroid longitude, degrees β see MarshalJSON note above. */
longitude: number
/** Computed bounding radius, meters β see MarshalJSON note above. */
radius: number
}
/**
* One time-versioned electricity-rate row for a geofence. The canonical,
* append-only source of truth β there is no separate mutable "current
* rate" column anywhere. The active rate for any instant `t` is whichever
* row's half-open `[effective_from, effective_to)` interval contains `t`;
* `effective_to: null` means "still open" (the current version).
*/
export interface GeofenceRate {
id: number
geofence_id: number
/** Currency units per **watt-hour** β SI-canonical, never per-kWh. */
rate_per_wh: number
/** ISO-4217 currency code, e.g. "USD". */
currency: string
effective_from: string
effective_to?: string | null
created_at: string
}
/** Request body for `POST /geofences/{geofenceID}/rates`. */
export interface GeofenceRateCreateRequest {
rate_per_wh: number
currency: string
effective_from: string
effective_to?: string | null
}
/**
* Charging-session cost provenance values, mirroring the
* `charging_sessions.cost_source` CHECK constraint. Precedence (highest to
* lowest confidence): manual actual > tesla_actual > geofence_tariff >
* default_estimate > unknown.
*/
export type CostSource =
| 'manual'
| 'tesla_actual'
| 'geofence_tariff'
| 'default_estimate'
| 'unknown'
/**
* Read-only "what would applying this rate do" response for
* `GET /geofences/{geofenceID}/rates/{rateID}/preview` β no rows written.
* `eligible_sessions` is the subset of `matched_sessions` an apply call is
* actually allowed to touch (unpriced or previously geofence-derived);
* `protected_sessions` already carry a manual/Tesla-actual cost and are
* matched (in scope by place + time) but will never be overwritten.
*/
export interface GeofenceRateImpactPreview {
geofence_id: number
rate_id: number
currency: string
matched_sessions: number
eligible_sessions: number
protected_sessions: number
total_energy_wh: number
estimated_cost_decimal: number
}
/**
* Outcome of an explicit apply/backfill action β
* `POST /geofences/{geofenceID}/rates/{rateID}/apply`. The
* write-performing counterpart of {@link GeofenceRateImpactPreview}.
*/
export interface GeofenceRateApplyResult {
geofence_id: number
rate_id: number
currency: string
matched_sessions: number
priced_sessions: number
skipped_sessions: number
total_energy_wh: number
total_cost_decimal: number
}
/**
* A geofence's priced charging activity totals for ONE currency β
* `GET /geofences/{geofenceID}/charging-summary` always returns an array,
* one entry per currency ever seen at this place. Different currencies are
* NEVER summed into a single total; callers must group/scope by currency.
*/
export interface GeofenceChargingSummary {
geofence_id: number
currency: string
session_count: number
total_energy_wh: number
total_cost_decimal: number
}
/**
* One line item in a geofence's charging-session activity feed β
* `GET /geofences/{geofenceID}/charging-activity` (paginated via
* `limit`/`offset` query params; any pricing state, not just priced rows).
*/
export interface GeofenceChargingActivity {
session_id: number
vehicle_id: number
started_at: string
ended_at?: string | null
energy_wh?: number | null
cost_decimal?: number | null
cost_currency?: string | null
cost_source?: CostSource | null
rate_id?: number | null
}
export interface AppSettings {
unit_of_length: string
unit_of_temp: string
unit_of_pressure: string
preferred_range: string
language: string
base_cost_per_kwh: number
api_suspended: boolean
theme: string
mode: string
custom_primary: string
custom_accent: string
/**
* DB-persisted list of onboarding tours the user has completed or skipped,
* as `"{tourId}:{version}"` tokens (e.g. "main:1"). Mirrors the per-tour
* localStorage flags so completion survives a cookies/site-data clear and
* syncs across devices. Optional for backward-compat with older responses.
*/
completed_tours?: string[]
gas_price_per_unit: number
gas_unit: string
gas_efficiency_mpg: number
decimal_precision: number
quiet_hours_enabled: boolean
quiet_hours_start: string
quiet_hours_end: string
alert_digest_mode: string
polling_config?: PollingConfig
/** Unicode currency glyph (e.g. "$", "β¬"). Stored verbatim β no ISO 4217 lookup. */
currency_symbol?: string
/** BCP-47 locale tag for `Intl.NumberFormat` (e.g. "en-US", "de-DE"). */
locale?: string
/**
* Default timezone-display mode used by `<DateTime>` when no explicit
* `in` prop is set. 'vehicle' = car local time (falls back to user TZ
* when the vehicle has no learned tz); 'user' = browser local; 'utc'
* = literal UTC. Defaults to 'vehicle'.
*/
tz_display_default?: 'vehicle' | 'user' | 'utc'
/**
* Optional override of the user's browser-detected timezone (IANA
* name, e.g. "America/Los_Angeles"). Empty string = use browser TZ.
* Server-side validated against Go's tzdata.
*/
timezone_user?: string
/**
* When true (default), the app prefixes `document.title` with the
* unread-notification count `(N)` and paints a coloured dot on the
* favicon. Disable to keep the tab title/icon static.
*/
tab_badge_enabled?: boolean
/**
* When true (default), the app briefly flashes
* `"(!) ALERT β "` in front of `document.title` when a critical
* alert fires while the tab is in the background. Disabled
* automatically for users with `prefers-reduced-motion: reduce`.
*
*/
critical_flash_enabled?: boolean
/**
* Global UI information-density preference. Flows from this single
* setting to:
* - CSS variables (`--density-row-h`, `--density-pad-x`, ...) on
* `body[data-density="..."]`, consumed by Tailwind utilities
* `min-h-d-row`, `px-d-pad-x`, `py-d-pad-y`, `gap-d-gap`,
* `text-d-base`.
* - Shared components when called with `density="auto"` /
* `padding="auto"` / `size="auto"`.
*
* Defaults to `'comfortable'` so existing users see no visual
* change.
*/
ui_density?: 'compact' | 'comfortable' | 'spacious'
/**
* Default visible format for `<TimeStamp>` when no explicit `format`
* prop is set. 'relative' renders "2h ago" with an absolute hover
* tooltip; 'absolute' renders "Apr 4, 2:30 AM" with a relative hover
* tooltip. Defaults to 'relative'.
*/
time_format_default?: 'relative' | 'absolute'
/**
* User's preferred chart series palette.
* - 'cb_safe' (default) β Okabe-Ito color-blind-safe palette.
* - 'neon' β original stylistic neon palette.
* Consumed by the reactive `useChartPalette()` hook in
* `@/hooks/useChartPalette`. The static `CHART_COLORS` constant
* always renders CB-safe regardless of this preference.
*
*/
chart_palette?: 'cb_safe' | 'neon'
/**
* Typography preferences (Typography Unit 0). Round-tripped by the
* FontProvider, which applies them to the `--font-*` CSS variables at the
* display boundary. All optional β an absent field falls back to the
* server-side default (mirrors DEFAULT_FONT_PREFS in FontProvider.tsx).
*/
font_family?: string
font_mono?: string
font_custom_sans?: string
font_custom_mono?: string
font_scale?: number
font_leading?: number
font_tracking?: string
font_heading_weight?: number
/**
* AI-Off Contract (ADR-015).
*
* Top-level gate. `'off'` (default) blocks every AI surface
* end-to-end: backend handlers return 404, frontend wrappers render
* `null`, ESLint blocks unwrapped AI components, and the database
* stores no AI rows. `'local'` permits providers on RFC1918 /
* loopback only; `'cloud'` permits any provider. The gate must be
* flipped before any per-feature toggle in {@link ai_features} has
* effect.
*/
ai_mode?: 'off' | 'local' | 'cloud'
/**
* per-feature opt-in map keyed by registry feature
* ID (see `web/src/ai/features.ts`, generated from
* `internal/ai/features/registry.go`). Default `{}` means every
* feature is off; setting `ai_features['chatbot-llm'] = true`
* combined with `ai_mode != 'off'` is what `useAiEnabled('chatbot-llm')`
* checks.
*/
ai_features?: Record<string, boolean>
/**
* adapter-specific configuration (`base_url`,
* `model`, `api_key_ref`, etc.). The backend redacts this field
* from Settings GET responses whenever `ai_mode === 'off'`
* (ADR-015 Β§I9), so the SPA must not rely on it being present in
* off mode and must handle `undefined` gracefully.
*/
ai_provider_config?: Record<string, unknown>
/**
* daily AI cost cap in cents. `0` (default) means
* unset (the per-feature rate limiters still apply). Enforced by
* the cost-tracker slice F9.
*/
ai_cost_cap_cents?: number
/**
* snapshot of the per-feature opt-in map preserved
* at the moment `ai_mode` was set to `'off'`. Per ADR-015 Β§I7 the
* modeβoff transition CLEARS `ai_features` so a subsequent
* re-enable cannot silently restore the prior selection. The
* archive lets the Settings β AI panel offer an explicit
* "Restore previous selection?" suggestion β restore is never
* silent. The backend redacts this field whenever
* `ai_mode === 'off'` (same rationale as `ai_provider_config`),
* so consumers must handle `undefined` gracefully.
*/
ai_features_archived?: Record<string, boolean>
}
/** Per-endpoint toggle config for Tesla Fleet API calls. */
export interface PollingConfig {
// Polling endpoints (automatic)
vehicle_discovery: boolean
charge_state: boolean
climate_state: boolean
drive_state: boolean
location_data: boolean
vehicle_state: boolean
vehicle_config: boolean
// On-demand counterparts for polling endpoints (user-triggered)
on_demand_vehicle_discovery: boolean
on_demand_charge_state: boolean
on_demand_climate_state: boolean
on_demand_drive_state: boolean
on_demand_location_data: boolean
on_demand_vehicle_state: boolean
on_demand_vehicle_config: boolean
// On-demand only endpoints
nearby_charging_sites: boolean
release_notes: boolean
recent_alerts: boolean
service_data: boolean
// Commands
wake_up: boolean
commands: boolean
// Telemetry capture (raw signal recording to MongoDB)
telemetry_capture: boolean
telemetry_capture_retention_days: number
}
export interface VehicleState {
vehicle_id: number
state: string
since?: string
latitude: number
longitude: number
heading?: number | null
speed: number
power: number
battery_level: number
rated_range: number
ideal_range: number
odometer: number
inside_temp: number
outside_temp: number
is_climate_on: boolean
is_charging: boolean
charger_power: number
charge_rate: number
time_to_full_charge: number
is_locked: boolean
sentry_mode: boolean
software_version: string
}
export interface AuthStatus {
authenticated: boolean
expires_at?: string
expired?: boolean
}
// === New Feature Types ===
export interface EnergyStats {
/** Energy in watt-hours (Wh, SI). */
total_energy_used_wh: number
/** Energy in watt-hours (Wh, SI). */
total_energy_charged_wh: number
total_wh: number
/** Energy intensity in watt-hours per meter (Wh/m, SI). */
avg_efficiency_wh_per_m: number
/** Distance in meters (m, SI). */
total_distance_m: number
total_cost: number
/** CO2 saved in kilograms (kg, SI). */
co2_saved_kg: number
daily_breakdown: { date: string; energy_wh: number; distance_m: number; efficiency_wh_per_m: number }[]
}
export interface BatteryReport {
vehicle_id: number
current_capacity_pct: number
degradation_pct: number
/** Estimated range when new in kilometers (km, derived SI). */
estimated_range_new_km: number
/** Current estimated range in kilometers (km, derived SI). */
estimated_range_current_km: number
total_cycles: number
health_score: number
monthly_trend: { month: string; capacity_pct: number; range_km: number }[]
}
export interface Alert {
id: number
vehicle_id: number
/** Free-form alert type. The backend slugifies the alert rule name; legacy
* values include 'geofence_exit', 'low_battery', 'charging_complete', etc.
* Always treat as `string` and tolerate unknown values at the UI layer. */
type: string
severity: 'info' | 'warning' | 'critical' | string
title: string
message: string
is_read: boolean
created_at: string
/** Canonical alert-rule scope. `null`/omitted means the originating rule
* no longer exists or the row is a fleet-wide system notification. */
all_vehicles?: boolean | null
vehicle_ids?: number[] | null
/** Drill-through metadata. Populated when the
* notification log links to a still-existing alert rule. Used by
* `getAlertDrillthroughHref()` (web/src/lib/alertDrillthrough.ts) to
* deep-link from the alert into the relevant context page. */
rule_id?: number | null
rule_signal?: string | null
rule_severity?: AlertRuleSeverity | string | null
/** acknowledgement state. Populated by
* GET /alerts/{id} and by the ack/reopen mutations. List endpoint also
* returns these when the row is acknowledged so the inbox can show a
* badge without a per-row detail fetch. */
acknowledged_at?: string | null
acknowledged_by?: string | null
acknowledgement_note?: string | null
}
/** entry in an alert's audit timeline. The synthetic
* `created` event has `id: 0` and is reconstructed from
* `notification_logs.created_at` server-side; persisted events have a
* positive `id` from `notification_log_events`. */
export type AlertEventKind = 'created' | 'acknowledged' | 'reopened' | 'commented' | string
export interface AlertEvent {
id: number
occurred_at: string
actor?: string | null
kind: AlertEventKind
note?: string | null
}
/** wire shape of GET /alerts/{id}. Extends Alert with
* the ack columns (already optional on Alert) and an always-present events
* array (oldest first, includes synthetic `created`). */
export interface AlertDetail extends Alert {
events: AlertEvent[]
}
export type AlertRuleSeverity = 'info' | 'warn' | 'critical'
export type AlertRuleOp = '=' | '!=' | '<' | '<=' | '>' | '>=' | 'changed' | 'between' | 'outside'
export type AlertRuleTriggerMode = 'once' | 'repeat'
export type AlertRuleKind = 'signal' | 'computed_metric'
export type ComputedMetricOp = '>' | '>=' | '<' | '<=' | '=' | '!=' | '%_change_>' | '%_change_<'
export interface AlertRule {
id: number
name: string
description?: string | null
enabled: boolean
vehicle_id?: number | null
/**
* sticky-all flag. When `true`, the rule
* applies to every vehicle in the fleet, including any added after
* the rule was created. Mutually exclusive with a non-empty
* `vehicle_ids` array. Optional on read for backward-compat with
* pre-0005 API responses; transitional hydration falls back to
* `vehicle_id`.
*/
all_vehicles?: boolean
/**
* explicit subset of vehicle IDs the rule
* applies to. Always present (`[]` if sticky-all). Optional on read
* only for backward-compat with pre-0005 API responses.
*/
vehicle_ids?: number[]
signal_name: string
op: AlertRuleOp
value_num?: number | null
value_text?: string | null
value_bool?: boolean | null
value_min?: number | null
value_max?: number | null
severity: AlertRuleSeverity
cooldown_min: number
trigger_mode: AlertRuleTriggerMode
snoozed_until?: string | null
kind?: AlertRuleKind
metric_id?: string | null
metric_window?: string | null
metric_threshold?: number | null
metric_op?: ComputedMetricOp | null
/**
* Per-rule cap on how many notifications a `repeat`-mode rule may emit
* between successive falling-edge resets. NULL = unlimited (legacy
* behaviour). Once-mode rules ignore this field β the latch already
* caps them at 1 per resolution.
* Decision D5.
*/
max_fires_per_resolution?: number | null
/**
* two-tier severity escalation. When set,
* a repeat-mode rule whose underlying condition has stayed
* unresolved for at least `escalation_after_min` minutes fires at
* `escalation_severity` instead of the base `severity`. Both fields
* MUST be set or both MUST be null. Once-mode rules ignore these
* fields entirely (the latch caps them at 1 fire per resolution).
* `escalation_severity` MUST rank strictly higher than `severity`
* under info < warn < critical.
*/
escalation_after_min?: number | null
escalation_severity?: AlertRuleSeverity | null
/**
* ADR-014 β per-rule notification body template. NULL
* means "use the op-aware default rendered by internal/alertmsg".
* Supports `{{key}}` substitution; whitespace inside the braces is
* allowed. Max length: 1024 chars.
*/
msg_template?: string | null
/**
* ADR-014 β when FALSE, transports that render a separate
* title field (Discord/Slack/Telegram/ntfy/webhook) deliver
* body-only notifications. Transports that REQUIRE a title (WebPush,
* email Subject, Pushover) ignore this flag. Defaults to TRUE.
*/
include_title?: boolean
created_at: string
updated_at: string
}
export interface AlertRuleInput {
name: string
description?: string | null
enabled?: boolean
vehicle_id?: number | null
/**
* sticky-all flag. New writes from the
* editor MUST set this together with `vehicle_ids`; the legacy
* `vehicle_id` field is no longer written by Alert Studio.
*/
all_vehicles?: boolean
/**
* explicit subset of vehicle IDs. Empty
* array when `all_vehicles` is true. Always sorted + deduped on the
* client per Decision D14.
*/
vehicle_ids?: number[]
signal_name?: string
op?: AlertRuleOp
value_num?: number | null
value_text?: string | null
value_bool?: boolean | null
value_min?: number | null
value_max?: number | null
severity?: AlertRuleSeverity
cooldown_min?: number
trigger_mode?: AlertRuleTriggerMode
snoozed_until?: string | null
kind?: AlertRuleKind
metric_id?: string | null
metric_window?: string | null
metric_threshold?: number | null
metric_op?: ComputedMetricOp | null
max_fires_per_resolution?: number | null
/**
* escalation pair. See AlertRule.escalation_*
* for invariants. Both fields MUST appear together (both null or
* both populated). Repeat-mode only.
*/
escalation_after_min?: number | null
escalation_severity?: AlertRuleSeverity | null
/** ADR-014 β see AlertRule.msg_template. */
msg_template?: string | null
/** ADR-014 β see AlertRule.include_title. */
include_title?: boolean
}
export interface ComputedMetricSummary {
id: string
label: string
unit: string
windows: string[]
ops: ComputedMetricOp[]
}
export interface ComputedMetricPreview {
kind: 'computed_metric'
metric_id: string
metric_window: string
metric_op: ComputedMetricOp
threshold: number
value: number
would_trigger: boolean
previous_value?: number
percent_change?: number
}
export type AlertRuleUpdate = Partial<AlertRuleInput>
export interface AlertRuleSnoozeRequest {
/** Snooze for N minutes from now. Use <= 0 to clear an existing snooze. */
minutes?: number
/** ISO timestamp; past timestamps clear an existing snooze. */
until?: string
}
export interface AlertTestTarget {
all_channels?: boolean
channel_ids?: number[]
}
export interface AlertTestRequest {
message?: string
target?: AlertTestTarget | null
/**
* ADR-014 β when set, the Test Rule endpoint previews the
* given template instead of the legacy free-form `message`. Empty
* string is normalised to "use the op-aware default".
*/
msg_template?: string | null
/** ADR-014 β see AlertRule.include_title. */
include_title?: boolean
}
/**
* ADR-014 β autocomplete suggestion served by
* GET /api/v1/alerts/message-placeholders. Mirrors
* internal/alertmsg.Placeholder.
*/
export interface AlertMessagePlaceholder {
key: string
label: string
description?: string
group: string
example?: string
}
/**
* ADR-014 β curated message-template preset served by
* GET /api/v1/alerts/message-presets. Mirrors internal/alertmsg.Preset.
*/
export interface AlertMessagePreset {
id: string
name: string
description?: string
template: string
kind?: '' | 'signal' | 'computed_metric'
tags?: string[]
}
/**
* ADR-014 β request body for POST /api/v1/alerts/message-preview.
* Accepts the editor's draft rule shape so the preview renders against
* the same inputs the production dispatch path uses.
*/
export interface AlertMessagePreviewRequest {
name?: string
kind?: AlertRuleKind
signal_name?: string
op?: AlertRuleOp
severity?: AlertRuleSeverity
vehicle_name?: string
value_num?: number | null
value_text?: string | null
value_bool?: boolean | null
value_min?: number | null
value_max?: number | null
metric_id?: string | null
metric_window?: string | null
metric_threshold?: number | null
metric_op?: ComputedMetricOp | null
msg_template?: string | null
include_title?: boolean
/** Optional sample signal values to feed the renderer. */
signals?: Record<string, unknown>
}
export interface AlertMessagePreviewResponse {
title: string
body: string
}
export interface StatsSummary {
min: number; max: number; avg: number; median: number; p95: number; count: number
}
export interface FleetAnalytics {
period_days: number
total_vehicles: number
/** Distance in kilometers (km, derived SI). */
total_distance_km: number
total_drives: number
total_charging_sessions: number
/** Energy in kilowatt-hours (kWh, derived SI). */
total_energy_kwh: number
total_cost: number
/** Energy intensity in watt-hours per kilometer (Wh/km, derived SI). */
avg_efficiency_wh_km: number
most_efficient_vehicle: { id: number; name: string; efficiency: number } | null
vehicle_comparison: { id: number; name: string; distance: number; energy: number; efficiency: number; drives: number }[]
drive_analytics: {
hourly_pattern: { hour: number; drives: number; distance: number }[]
day_of_week: { day: string; drives: number; distance: number; avg_distance: number }[]
speed_distribution: { range: string; count: number }[]
distance_distribution: { range: string; count: number }[]
speed_stats: StatsSummary
power_stats: StatsSummary
regen_stats: StatsSummary
duration_stats: StatsSummary
distance_stats: StatsSummary
efficiency_stats: StatsSummary
daily_trend: { date: string; drives: number; distance: number; efficiency?: number }[]
temp_vs_efficiency: { temp: number; efficiency: number; distance: number }[]
duration_distribution?: { range: string; count: number }[]
temperature: { inside: StatsSummary; outside: StatsSummary }
}
charging_analytics: {
hourly_pattern: { hour: number; charges: number; energy: number }[]
charger_types: { type: string; count: number }[]
charger_brands: { brand: string; count: number }[]
monthly_trend: { month: string; energy: number; cost: number; sessions: number; avg_power: number; gas_cost: number; savings: number }[]
power_stats: StatsSummary
duration_stats: StatsSummary
energy_stats: StatsSummary
cost_stats: StatsSummary
start_battery_dist: { range: string; count: number }[]
efficiency_stats: StatsSummary
}
battery_trend: { date: string; health_score: number; capacity_wh: number; degradation_pct: number; range_km: number; cycle_count: number }[]
}
export interface CommandResult {
success: boolean