diff --git a/csharp/App/Backend/Controller.cs b/csharp/App/Backend/Controller.cs index 90ee9d6a3..35105a84b 100644 --- a/csharp/App/Backend/Controller.cs +++ b/csharp/App/Backend/Controller.cs @@ -1908,14 +1908,13 @@ public class Controller : ControllerBase config.NetworkProvider = installation?.NetworkProvider; } - string configString = product switch + // Serialize what was actually sent — drops null/unset fields so the audit + // entry is product-shaped automatically (no per-product formatter to maintain). + var configString = System.Text.Json.JsonSerializer.Serialize(config, new System.Text.Json.JsonSerializerOptions { - 0 => config.GetConfigurationSalimax(), // Salimax - 3 => config.GetConfigurationSodistoreMax(), // SodiStoreMax - 2 => config.GetConfigurationSodistoreHome(), // SodiStoreHome - 4 => config.GetConfigurationSodistoreGrid(), // SodistoreGrid - _ => config.GetConfigurationString() // fallback - }; + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + WriteIndented = false, + }); Console.WriteLine("CONFIG IS " + configString); diff --git a/csharp/App/Backend/DataTypes/Configuration.cs b/csharp/App/Backend/DataTypes/Configuration.cs index 63a0fdb1e..589511bf4 100644 --- a/csharp/App/Backend/DataTypes/Configuration.cs +++ b/csharp/App/Backend/DataTypes/Configuration.cs @@ -9,17 +9,20 @@ public class Configuration public CalibrationChargeType? CalibrationDischargeState { get; set; } public DateTime? CalibrationDischargeDate { get; set; } + // V1 (legacy) flat fields — still used by the original SodistoreHomeConfiguration page + // for installations not opted in to V2. WhenWritingNull keeps them out of V2 payloads. public double? MaximumDischargingCurrent { get; set; } public double? MaximumChargingCurrent { get; set; } - // Nested per-inverter / per-cluster topology + limits (Sinexcel). - // Keys: "Inverter1".."InverterN" → { Clusters: { "Cluster1".. }, PvCount } - public Dictionary? Inverters { get; set; } - public double? OperatingPriority { get; set; } public int? InverterNumber { get; set; } public double? BatteriesCount { get; set; } public List? BatteriesCountPerInverter { get; set; } public double? ClusterNumber { get; set; } public double? PvNumber { get; set; } + // V2 — per-inverter Clusters + PvCount, keyed by "Inverter1".."InverterN". + // Wire format mirrors the on-disk shape — device merges these into its existing Devices.InverterN entries. + // Per-cluster MaxChargingCurrent / MaxDischargingCurrent live inside Devices[InverterN].Clusters[ClusterN]. + public Dictionary? Devices { get; set; } + public double? OperatingPriority { get; set; } public bool ControlPermission { get; set; } public double? TimeChargeandDischargePower { get; set; } public DateTime? StartTimeChargeandDischargeDayandTime { get; set; } @@ -37,42 +40,6 @@ public class Configuration public string? TimeToBuyFrom { get; set; } public string? TimeToBuyTo { get; set; } - public String GetConfigurationString() - { - return $"MinimumSoC: {MinimumSoC}, GridSetPoint: {GridSetPoint}, CalibrationChargeState: {CalibrationChargeState}, CalibrationChargeDate: {CalibrationChargeDate}, " + - $"CalibrationDischargeState: {CalibrationDischargeState}, CalibrationDischargeDate: {CalibrationDischargeDate}, " + - $"MaximumDischargingCurrent: {MaximumDischargingCurrent}, MaximumChargingCurrent: {MaximumChargingCurrent}, OperatingPriority: {OperatingPriority}, " + - $"InverterNumber: {InverterNumber}, BatteriesCount: {BatteriesCount}, BatteriesCountPerInverter: [{(BatteriesCountPerInverter != null ? string.Join(", ", BatteriesCountPerInverter) : "")}], ClusterNumber: {ClusterNumber}, PvNumber: {PvNumber}, ControlPermission:{ControlPermission}, "+ - $"SinexcelTimeChargeandDischargePower: {TimeChargeandDischargePower}, SinexcelStartTimeChargeandDischargeDayandTime: {StartTimeChargeandDischargeDayandTime}, SinexcelStopTimeChargeandDischargeDayandTime: {StopTimeChargeandDischargeDayandTime}"; - - } - - public string GetConfigurationSalimax() - { - return - $"MinimumSoC: {MinimumSoC}, GridSetPoint: {GridSetPoint}, CalibrationChargeState: {CalibrationChargeState}, CalibrationChargeDate: {CalibrationChargeDate}"; - } - - public string GetConfigurationSodistoreMax() - { - return - $"MinimumSoC: {MinimumSoC}, GridSetPoint: {GridSetPoint}, CalibrationChargeState: {CalibrationChargeState}, CalibrationChargeDate: {CalibrationChargeDate}"; - } - - public string GetConfigurationSodistoreHome() - { - return $"MinimumSoC: {MinimumSoC}, MaximumDischargingCurrent: {MaximumDischargingCurrent}, MaximumChargingCurrent: {MaximumChargingCurrent}, OperatingPriority: {OperatingPriority}, " + - $"InverterNumber: {InverterNumber}, BatteriesCount: {BatteriesCount}, BatteriesCountPerInverter: [{(BatteriesCountPerInverter != null ? string.Join(", ", BatteriesCountPerInverter) : "")}], ClusterNumber: {ClusterNumber}, PvNumber: {PvNumber}, ControlPermission:{ControlPermission}, "+ - $"SinexcelTimeChargeandDischargePower: {TimeChargeandDischargePower}, SinexcelStartTimeChargeandDischargeDayandTime: {StartTimeChargeandDischargeDayandTime}, SinexcelStopTimeChargeandDischargeDayandTime: {StopTimeChargeandDischargeDayandTime}, " + - $"DynamicPricingMode: {DynamicPricingMode}, NetworkProvider: {NetworkProvider}, CurrentPrice: {CurrentPrice}, PriceToSell: {PriceToSell}, PriceToBuy: {PriceToBuy}, " + - $"TimeToSell: {TimeToSellFrom}-{TimeToSellTo}, TimeToBuy: {TimeToBuyFrom}-{TimeToBuyTo}"; - } - - // TODO: SodistoreGrid — update configuration fields when defined - public string GetConfigurationSodistoreGrid() - { - return ""; - } } public enum CalibrationChargeType @@ -82,10 +49,10 @@ public enum CalibrationChargeType ChargePermanently } -public class InverterConfig +public class DeviceConfigPartial { - public Dictionary Clusters { get; set; } = new(); - public int PvCount { get; set; } + public Dictionary? Clusters { get; set; } + public int? PvCount { get; set; } } public class ClusterConfig diff --git a/csharp/App/Backend/DataTypes/Methods/ExoCmd.cs b/csharp/App/Backend/DataTypes/Methods/ExoCmd.cs index 44915ab37..133719cad 100644 --- a/csharp/App/Backend/DataTypes/Methods/ExoCmd.cs +++ b/csharp/App/Backend/DataTypes/Methods/ExoCmd.cs @@ -448,12 +448,16 @@ public static class ExoCmd for (int j = 0; j < maxRetransmissions; j++) { //string message = "This is a message from RabbitMQ server, you can subscribe to the RabbitMQ queue"; - byte[] data = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(config)); + // Drop null fields so the device only sees what's actually set for this product. + var jsonOptions = new System.Text.Json.JsonSerializerOptions + { + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull + }; + var payload = JsonSerializer.Serialize(config, jsonOptions); + byte[] data = Encoding.UTF8.GetBytes(payload); udpClient.Send(data, data.Length, installation.VpnIp, port); - Console.WriteLine(config.GetConfigurationString()); - - Console.WriteLine($"Sent UDP message to {installation.VpnIp}:{port}: {config}"); + Console.WriteLine($"Sent UDP message to {installation.VpnIp}:{port}: {payload}"); //Console.WriteLine($"Sent UDP message to {installation.VpnIp}:{port}"+" GridSetPoint is "+config.GridSetPoint +" and MinimumSoC is "+config.MinimumSoC); IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(installation.VpnIp), port); diff --git a/typescript/frontend-marios2/src/content/dashboards/Log/graph.util.tsx b/typescript/frontend-marios2/src/content/dashboards/Log/graph.util.tsx index f4a0a49fc..4bae6392b 100644 --- a/typescript/frontend-marios2/src/content/dashboards/Log/graph.util.tsx +++ b/typescript/frontend-marios2/src/content/dashboards/Log/graph.util.tsx @@ -707,9 +707,9 @@ export type ConfigurationValues = { //For sodistoreHome maximumDischargingCurrent: number; maximumChargingCurrent: number; - // Nested per-inverter / per-cluster topology + limits (Sinexcel). - // Keys: "Inverter1".."InverterN" → { Clusters: { "Cluster1".. }, PvCount } - inverters?: { [inverterKey: string]: InverterConfig }; + // Per-inverter Clusters + PvCount, keyed by "Inverter1".."InverterN". + // Wire format mirrors the on-disk Devices.InverterN shape — device merges by key. + devices?: { [inverterKey: string]: InverterConfig }; operatingPriority: number; batteriesCount: number; inverterNumber: number; diff --git a/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/Installation.tsx b/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/Installation.tsx index 272f6efcb..3fedde12d 100644 --- a/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/Installation.tsx +++ b/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/Installation.tsx @@ -25,6 +25,11 @@ import { fetchDataJson } from '../Installations/fetchData'; import { FetchResult } from '../../../dataCache/dataCache'; import BatteryViewSodioHome from '../BatteryView/BatteryViewSodioHome'; import SodistoreHomeConfiguration from './SodistoreHomeConfiguration'; +import SodistoreHomeConfigurationV2 from './SodistoreHomeConfigurationV2'; + +// Pilot installations using the new per-cluster Configuration page (V2). +// All other installations keep using the original SodistoreHomeConfiguration (V1). +const CONFIG_V2_INSTALLATION_IDS = new Set([790, 839]); import TopologySodistoreHome from '../Topology/TopologySodistoreHome'; import Overview from '../Overview/overview'; import WeeklyReport from './WeeklyReport'; @@ -599,11 +604,19 @@ function SodioHomeInstallation(props: singleInstallationProps) { + CONFIG_V2_INSTALLATION_IDS.has(props.current_installation.id) ? ( + + ) : ( + + ) } /> )} diff --git a/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/SodistoreHomeConfiguration.tsx b/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/SodistoreHomeConfiguration.tsx index accd5fd16..aafbbd349 100644 --- a/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/SodistoreHomeConfiguration.tsx +++ b/typescript/frontend-marios2/src/content/dashboards/SodiohomeInstallations/SodistoreHomeConfiguration.tsx @@ -1,19 +1,13 @@ -import { ConfigurationValues, InverterConfig, JSONRecordData } from '../Log/graph.util'; +import { ConfigurationValues, JSONRecordData } from '../Log/graph.util'; import { - Accordion, - AccordionDetails, - AccordionSummary, Alert, Box, CardContent, - Chip, CircularProgress, Container, - Divider, FormControl, Grid, IconButton, - InputAdornment, InputLabel, Modal, Select, @@ -21,7 +15,6 @@ import { Typography, useTheme } from '@mui/material'; -import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; import React, { useContext, useState, useEffect } from 'react'; import { FormattedMessage, useIntl } from 'react-intl'; @@ -32,16 +25,9 @@ import axiosConfig from '../../../Resources/axiosConfig'; import { UserContext } from '../../../contexts/userContext'; import { ProductIdContext } from '../../../contexts/ProductIdContextProvider'; import { I_Installation } from 'src/interfaces/InstallationTypes'; -import { - buildSodistoreProPreset, - getPresetsForDevice, - parseBatterySnTree, - PresetConfig, - BatterySnTree -} from '../Information/installationSetupUtils'; import { LocalizationProvider } from '@mui/x-date-pickers'; import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; -import { DateTimePicker, TimePicker } from '@mui/x-date-pickers'; +import {DateTimePicker } from '@mui/x-date-pickers'; import dayjs from 'dayjs'; import Switch from '@mui/material/Switch'; import FormControlLabel from '@mui/material/FormControlLabel'; @@ -72,14 +58,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { 'PvPriorityCharging': 'GridPriority', }; - // Dynamic Pricing Mode — backend enum values with UI labels - const DynamicPricingOptions = ['Disabled', 'SpotPrice', 'Tou'] as const; - const dynamicPricingLabelKey: Record = { - Disabled: 'dynamicPricingOff', - SpotPrice: 'dynamicPricingSpotPrice', - Tou: 'dynamicPricingTou', - }; - const [errors, setErrors] = useState({ minimumSoC: false, gridSetPoint: false @@ -92,7 +70,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { })); }; const theme = useTheme(); - const [formDirty, setFormDirty] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); const [updated, setUpdated] = useState(false); @@ -111,99 +88,30 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { // Storage key for pending config (optimistic update) const pendingConfigKey = `pendingConfig_${props.id}`; - // Hardware topology — derived from Information tab (single source of truth). - const isSodistorePro = product === 5; - const installationModel = props.installation.installationModel; - const presetConfig: PresetConfig | null = isSodistorePro - ? (installationModel && parseInt(installationModel, 10) > 0 - ? buildSodistoreProPreset(parseInt(installationModel, 10)) - : null) - : (getPresetsForDevice(device)[installationModel] || null); - const inverterCount = presetConfig?.length ?? 1; - - // Build the nested Inverters config from topology (presetConfig). - // Used as fallback when the device hasn't yet written the structured Inverters object. - const buildInvertersFromPreset = ( - chargeScalar: number | undefined, - dischargeScalar: number | undefined, - ): { [k: string]: InverterConfig } => { - if (!presetConfig) return {}; - const out: { [k: string]: InverterConfig } = {}; - presetConfig.forEach((clusters, invIdx) => { - const clObj: { [k: string]: any } = {}; - clusters.forEach((batteryCount, clIdx) => { - clObj[`Cluster${clIdx + 1}`] = { - BatteryCount: batteryCount, - MaxChargingCurrent: chargeScalar ?? 0, - MaxDischargingCurrent: dischargeScalar ?? 0, - }; - }); - out[`Inverter${invIdx + 1}`] = { Clusters: clObj, PvCount: 0 }; - }); - return out; - }; - // Helper to build form values from S3 data - const getS3Values = (): Partial => { - const inverterNum = props.values.Config.InverterNumber ?? 1; - const batteriesPerInverter: number[] = props.values.Config.BatteriesCountPerInverter - ?? Array(inverterNum).fill(props.values.Config.BatteriesCount || 1); - // Read per-inverter Clusters/PvCount from each Devices.InverterN entry on disk. - const cfgDevices = (props.values.Config as any).Devices as { [k: string]: any } | undefined; - const cfgInverters: { [k: string]: InverterConfig } | undefined = cfgDevices - ? Object.fromEntries( - Object.entries(cfgDevices) - .filter(([k, v]: [string, any]) => k.startsWith('Inverter') && (v?.Clusters || v?.PvCount != null)) - .map(([k, v]: [string, any]) => [k, { Clusters: v.Clusters ?? {}, PvCount: v.PvCount ?? 0 }]) - ) - : undefined; - const hasInverterData = cfgInverters && Object.keys(cfgInverters).length > 0; - return { - minimumSoC: props.values.Config.MinSoc, - maximumDischargingCurrent: props.values.Config.MaximumDischargingCurrent, - maximumChargingCurrent: props.values.Config.MaximumChargingCurrent, - // Always overlay Information-tab topology so battery counts and PV count - // reflect what's actually installed (Information tab is source of truth). - inverters: overlayTopology( - hasInverterData - ? cfgInverters - : buildInvertersFromPreset( - props.values.Config.MaximumChargingCurrent, - props.values.Config.MaximumDischargingCurrent, - ) - ), - operatingPriority: resolveOperatingPriorityIndex( - props.values.Config.OperatingPriority - ), - inverterNumber: inverterNum, - batteriesCountPerInverter: batteriesPerInverter, - batteriesCount: props.values.Config.BatteriesCount, - clusterNumber: props.values.Config.ClusterNumber ?? 1, - PvNumber: props.values.Config.PvNumber ?? 0, - pvCountPerInverter: (props.values.Config as any).PvCountPerInverter - ?? Array(inverterNum).fill(props.values.Config.PvNumber ?? 0), - timeChargeandDischargePower: props.values.Config?.TimeChargeandDischargePower ?? 0, - startTimeChargeandDischargeDayandTime: (() => { - const raw = props.values.Config?.StartTimeChargeandDischargeDayandTime; - const parsed = raw ? dayjs(raw) : null; - return parsed && parsed.year() >= 2020 ? parsed.toDate() : new Date(); - })(), - stopTimeChargeandDischargeDayandTime: (() => { - const raw = props.values.Config?.StopTimeChargeandDischargeDayandTime; - const parsed = raw ? dayjs(raw) : null; - return parsed && parsed.year() >= 2020 ? parsed.toDate() : new Date(); - })(), - controlPermission: String(props.values.Config.ControlPermission).toLowerCase() === "true", - dynamicPricingMode: (props.values.Config as any).DynamicPricingMode ?? 'Disabled', - currentPrice: (props.values.Config as any).CurrentPrice?.toString() ?? '', - priceToSell: (props.values.Config as any).PriceToSell?.toString() ?? '', - priceToBuy: (props.values.Config as any).PriceToBuy?.toString() ?? '', - timeToSellFrom: (props.values.Config as any).TimeToSellFrom ?? '', - timeToSellTo: (props.values.Config as any).TimeToSellTo ?? '', - timeToBuyFrom: (props.values.Config as any).TimeToBuyFrom ?? '', - timeToBuyTo: (props.values.Config as any).TimeToBuyTo ?? '', - }; - }; + const getS3Values = (): Partial => ({ + minimumSoC: props.values.Config.MinSoc, + maximumDischargingCurrent: props.values.Config.MaximumDischargingCurrent, + maximumChargingCurrent: props.values.Config.MaximumChargingCurrent, + operatingPriority: resolveOperatingPriorityIndex( + props.values.Config.OperatingPriority + ), + batteriesCount: props.values.Config.BatteriesCount, + clusterNumber: props.values.Config.ClusterNumber ?? 1, + PvNumber: props.values.Config.PvNumber ?? 0, + timeChargeandDischargePower: props.values.Config?.TimeChargeandDischargePower ?? 0, + startTimeChargeandDischargeDayandTime: (() => { + const raw = props.values.Config?.StartTimeChargeandDischargeDayandTime; + const parsed = raw ? dayjs(raw) : null; + return parsed && parsed.year() >= 2020 ? parsed.toDate() : new Date(); + })(), + stopTimeChargeandDischargeDayandTime: (() => { + const raw = props.values.Config?.StopTimeChargeandDischargeDayandTime; + const parsed = raw ? dayjs(raw) : null; + return parsed && parsed.year() >= 2020 ? parsed.toDate() : new Date(); + })(), + controlPermission: String(props.values.Config.ControlPermission).toLowerCase() === "true", + }); // Restore pending config from localStorage, converting date strings back to Date objects. // Returns { values, s3ConfigSnapshot } or null if no pending config. @@ -238,40 +146,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { // Fingerprint S3 Config for change detection (not value comparison) const getS3ConfigFingerprint = () => JSON.stringify(props.values.Config); - // Overlay Information-tab-derived topology onto a `inverters` config object. - // Battery counts come from the SN tree (filled SNs); PvCount comes from pvStringsPerInverter. - // Existing per-cluster current limits are preserved. - const overlayTopology = ( - inverters: { [k: string]: InverterConfig } | undefined - ): { [k: string]: InverterConfig } | undefined => { - if (!presetConfig) return inverters; - const tree = parseBatterySnTree(props.installation.batterySerialNumbers || '', presetConfig); - const pvStrings = (props.installation.pvStringsPerInverter || '') - .split(',') - .map((s) => s.trim()); - const out: { [k: string]: InverterConfig } = {}; - presetConfig.forEach((clusters, invIdx) => { - const invKey = `Inverter${invIdx + 1}`; - const existingInv = inverters?.[invKey]; - const cls: { [k: string]: any } = {}; - clusters.forEach((_slotCount, clIdx) => { - const clKey = `Cluster${clIdx + 1}`; - const filled = (tree[invIdx]?.[clIdx] ?? []).filter((s) => s !== '').length; - const existingCl = existingInv?.Clusters?.[clKey]; - cls[clKey] = { - BatteryCount: filled, - MaxChargingCurrent: existingCl?.MaxChargingCurrent ?? 0, - MaxDischargingCurrent: existingCl?.MaxDischargingCurrent ?? 0, - }; - }); - out[invKey] = { - Clusters: cls, - PvCount: parseInt(pvStrings[invIdx] || '0', 10) || 0, - }; - }); - return out; - }; - // Initialize form from localStorage (if pending submit exists) or from S3 // This runs in the useState initializer so the component never renders stale values const [formValues, setFormValues] = useState>(() => { @@ -297,10 +171,7 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { // When S3 data updates (polled every 60s), reconcile with any pending localStorage. // Strategy: device is the authority. Once S3 Config changes from the snapshot taken at // submit time, the device has uploaded new data — trust S3 regardless of values. - // Skip reset if the user is actively editing (formDirty). useEffect(() => { - if (formDirty) return; - const s3Values = getS3Values(); const pending = restorePendingConfig(); @@ -323,7 +194,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { }, [props.values]); const handleOperatingPriorityChange = (event) => { - setFormDirty(true); setFormValues({ ...formValues, ['operatingPriority']: OperatingPriorityOptions.indexOf( @@ -359,23 +229,14 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { if (!validateTimeOnly()) { return; } - // Re-overlay Information-tab topology at submit time, so battery counts and PV count - // are always the latest from the Information tab (it's the source of truth). - const inverters = overlayTopology(formValues.inverters); - // Pull the first cluster's value as a legacy single-scalar fallback for older firmware. - const firstInvKey = inverters ? Object.keys(inverters)[0] : undefined; - const firstClusterKey = firstInvKey && inverters - ? Object.keys(inverters[firstInvKey].Clusters)[0] - : undefined; - const firstCluster = firstInvKey && firstClusterKey && inverters - ? inverters[firstInvKey].Clusters[firstClusterKey] - : undefined; const configurationToSend: Partial = { minimumSoC: formValues.minimumSoC, - maximumDischargingCurrent: firstCluster?.MaxDischargingCurrent ?? formValues.maximumDischargingCurrent, - maximumChargingCurrent: firstCluster?.MaxChargingCurrent ?? formValues.maximumChargingCurrent, - inverters, + maximumDischargingCurrent: formValues.maximumDischargingCurrent, + maximumChargingCurrent: formValues.maximumChargingCurrent, operatingPriority: formValues.operatingPriority, + batteriesCount:formValues.batteriesCount, + clusterNumber:formValues.clusterNumber, + PvNumber:formValues.PvNumber, timeChargeandDischargePower: formValues.timeChargeandDischargePower, startTimeChargeandDischargeDayandTime: formValues.startTimeChargeandDischargeDayandTime ? new Date(formValues.startTimeChargeandDischargeDayandTime.getTime() - formValues.startTimeChargeandDischargeDayandTime.getTimezoneOffset() * 60000) @@ -383,15 +244,7 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { stopTimeChargeandDischargeDayandTime: formValues.stopTimeChargeandDischargeDayandTime ? new Date(formValues.stopTimeChargeandDischargeDayandTime.getTime() - formValues.stopTimeChargeandDischargeDayandTime.getTimezoneOffset() * 60000) : null, - controlPermission:formValues.controlPermission, - dynamicPricingMode: formValues.dynamicPricingMode, - currentPrice: formValues.currentPrice, - priceToSell: formValues.priceToSell, - priceToBuy: formValues.priceToBuy, - timeToSellFrom: formValues.timeToSellFrom, - timeToSellTo: formValues.timeToSellTo, - timeToBuyFrom: formValues.timeToBuyFrom, - timeToBuyTo: formValues.timeToBuyTo, + controlPermission:formValues.controlPermission }; setLoading(true); @@ -410,7 +263,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { if (res) { setUpdated(true); setLoading(false); - setFormDirty(false); // Save submitted values + S3 snapshot to localStorage for optimistic UI update. // s3ConfigSnapshot = fingerprint of S3 Config at submit time. @@ -425,7 +277,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { }; const handleChange = (e) => { - setFormDirty(true); const { name, value } = e.target; if (name === 'minimumSoC') { @@ -458,7 +309,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { }; const handleTimeChargeDischargeChange = (name: string, value: any) => { - setFormDirty(true); setFormValues((prev) => ({ ...prev, [name]: value @@ -538,18 +388,16 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { { - setFormDirty(true); + onChange={(e) => setFormValues((prev) => ({ ...prev, controlPermission: e.target.checked, - })); - } + })) } sx={{ transform: "scale(1.4)", marginLeft: "15px" }} /> } - sx={{ ml: 0 }} + label={ - {device === 4 && ( - <> - - - - - - )} - - {device === 4 && (() => { - // Read the SN tree from the Information tab data (single source of truth). - // Filled batteries per cluster = entries with a non-empty serial number. - const tree: BatterySnTree | null = presetConfig - ? parseBatterySnTree(props.installation.batterySerialNumbers || '', presetConfig) - : null; - // PV strings per inverter — comma-separated string from Information tab. - const pvStrings = (props.installation.pvStringsPerInverter || '') - .split(',') - .map((s) => s.trim()); - - return ( - <> -
- -
- - {Array.from({ length: inverterCount }, (_, i) => { - const clusters = presetConfig?.[i] ?? []; - const treeForInverter = tree?.[i] ?? []; - const filledBat = treeForInverter.flat().filter((s) => s !== '').length; - const totalBat = clusters.reduce((a, b) => a + b, 0); - return ( - - } - sx={{ - '& .MuiAccordionSummary-content': { flexGrow: 0, justifyContent: 'flex-start' }, - justifyContent: 'flex-start', - '& .MuiAccordionSummary-expandIconWrapper': { ml: 1 } - }} - > - - - - - - - {clusters.map((_slotCount, clIdx) => { - const filledInCluster = (treeForInverter[clIdx] ?? []) - .filter((s) => s !== '').length; - return ( -
- -
- ); - })} - {(() => { - const pvCount = parseInt(pvStrings[i] || '0', 10) || 0; - return ( -
- -
- ); - })()} -
-
- ); - })} - - ); - })()} +
+ + } + name="batteriesCount" + value={formValues.batteriesCount} + onChange={handleChange} + fullWidth + /> +
{device === 4 && ( <> - - - - +
+ + } + name="clusterNumber" + value={formValues.clusterNumber} + onChange={handleChange} + fullWidth + /> +
+ +
+ + } + name="PvNumber" + value={formValues.PvNumber} + onChange={handleChange} + fullWidth + /> +
)} +
{/* - {device === 4 ? ( - // Per-cluster, per-inverter charging/discharging current limits — nested config. - Array.from({ length: inverterCount }, (_, invIdx) => { - const invKey = `Inverter${invIdx + 1}`; - const clusters = presetConfig?.[invIdx] ?? [0]; - return ( - - } - sx={{ - '& .MuiAccordionSummary-content': { flexGrow: 0, justifyContent: 'flex-start' }, - justifyContent: 'flex-start', - '& .MuiAccordionSummary-expandIconWrapper': { ml: 1 } - }} - > - - - - - - {clusters.map((_slotCount, clIdx) => { - const clKey = `Cluster${clIdx + 1}`; - const cluster = formValues.inverters?.[invKey]?.Clusters?.[clKey]; - const charge = cluster?.MaxChargingCurrent ?? ''; - const discharge = cluster?.MaxDischargingCurrent ?? ''; - const setClusterField = ( - field: 'MaxChargingCurrent' | 'MaxDischargingCurrent', - v: string - ) => { - if (v !== '' && !/^\d*\.?\d*$/.test(v)) return; - setFormDirty(true); - setFormValues((prev) => { - const inverters = { ...(prev.inverters ?? {}) }; - const inv = inverters[invKey] - ?? { Clusters: {}, PvCount: 0 }; - const cls = { ...(inv.Clusters ?? {}) }; - const existing = cls[clKey] ?? { - BatteryCount: presetConfig?.[invIdx]?.[clIdx] ?? 0, - MaxChargingCurrent: 0, - MaxDischargingCurrent: 0, - }; - cls[clKey] = { - ...existing, - [field]: v === '' ? 0 : parseFloat(v), - }; - inverters[invKey] = { ...inv, Clusters: cls }; - return { ...prev, inverters }; - }); - }; - return ( -
- - - - setClusterField('MaxChargingCurrent', e.target.value)} - fullWidth - /> - setClusterField('MaxDischargingCurrent', e.target.value)} - fullWidth - /> -
- ); - })} -
-
- ); - }) - ) : ( - <> -
- + -
+ } + name="maximumChargingCurrent" + value={formValues.maximumChargingCurrent} + onChange={handleChange} + fullWidth + /> +
-
- + -
- - )} - - {device === 4 && ( - <> - - - - - - )} + } + name="maximumDischargingCurrent" + value={formValues.maximumDischargingCurrent} + onChange={handleChange} + fullWidth + /> +
@@ -851,13 +558,13 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { {/* Power input*/}
handleTimeChargeDischargeChange(e.target.name, e.target.value) } - helperText={intl.formatMessage({ id: 'perInverter' })} + helperText={intl.formatMessage({ id: 'enterPowerValue' })} fullWidth />
@@ -928,160 +635,6 @@ function SodistoreHomeConfiguration(props: SodistoreHomeConfigurationProps) { )} - {/* --- Sinexcel + LoadPriority: Dynamic Pricing --- */} - {device === 4 && - OperatingPriorityOptions[formValues.operatingPriority] === 'LoadPriority' && ( - <> - - - - - -
- - - - - - -
- - {formValues.dynamicPricingMode === 'Tou' && ( - <> - {(() => { - const renderTimeField = ( - labelId: string, - key: 'timeToSellFrom' | 'timeToSellTo' | 'timeToBuyFrom' | 'timeToBuyTo' - ) => { - const raw = formValues[key]; - const parsed = raw ? dayjs(raw, 'HH:mm') : null; - return ( - - { - setFormDirty(true); - setFormValues((prev) => ({ - ...prev, - [key]: newValue ? newValue.format('HH:mm') : '', - })); - }} - renderInput={(params) => ( - - )} - /> - - ); - }; - - return ( - <> - - - -
- {renderTimeField('timeFrom', 'timeToSellFrom')} - {renderTimeField('timeTo', 'timeToSellTo')} -
- - - - -
- {renderTimeField('timeFrom', 'timeToBuyFrom')} - {renderTimeField('timeTo', 'timeToBuyTo')} -
- - ); - })()} - - )} - - {formValues.dynamicPricingMode === 'SpotPrice' && ( - <> -
- -
- -
- CHF/kWh, - }} - fullWidth - /> -
- -
- { - const v = e.target.value; - if (v === '' || /^\d*\.?\d*$/.test(v)) { - setFormDirty(true); - setFormValues((prev) => ({ ...prev, priceToSell: v })); - } - }} - InputProps={{ - endAdornment: CHF/kWh, - }} - fullWidth - /> -
- -
- { - const v = e.target.value; - if (v === '' || /^\d*\.?\d*$/.test(v)) { - setFormDirty(true); - setFormValues((prev) => ({ ...prev, priceToBuy: v })); - } - }} - InputProps={{ - endAdornment: CHF/kWh, - }} - fullWidth - /> -
- - )} - - )} -
= { + 'SpontaneousSelfUse': 'LoadPriority', + 'TimeChargeDischarge': 'BatteryPriority', + 'PvPriorityCharging': 'GridPriority', + }; + + // Dynamic Pricing Mode — backend enum values with UI labels + const DynamicPricingOptions = ['Disabled', 'SpotPrice', 'Tou'] as const; + const dynamicPricingLabelKey: Record = { + Disabled: 'dynamicPricingOff', + SpotPrice: 'dynamicPricingSpotPrice', + Tou: 'dynamicPricingTou', + }; + + const [errors, setErrors] = useState({ + minimumSoC: false, + gridSetPoint: false + }); + + const SetErrorForField = (field_name, state) => { + setErrors((prevErrors) => ({ + ...prevErrors, + [field_name]: state + })); + }; + const theme = useTheme(); + const [formDirty, setFormDirty] = useState(false); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(false); + const [updated, setUpdated] = useState(false); + const [dateSelectionError, setDateSelectionError] = useState(''); + const [isErrorDateModalOpen, setErrorDateModalOpen] = useState(false); + const context = useContext(UserContext); + const { currentUser, setUser } = context; + const { product, setProduct } = useContext(ProductIdContext); + + // Resolve S3 OperatingPriority to display index (Sinexcel uses different enum names) + const resolveOperatingPriorityIndex = (s3Value: string) => { + const displayName = device === 4 ? (sinexcelS3ToDisplayName[s3Value] ?? s3Value) : s3Value; + return OperatingPriorityOptions.indexOf(displayName); + }; + + // Storage key for pending config (optimistic update) + const pendingConfigKey = `pendingConfig_${props.id}`; + + // Hardware topology — derived from Information tab (single source of truth). + const isSodistorePro = product === 5; + const installationModel = props.installation.installationModel; + const presetConfig: PresetConfig | null = isSodistorePro + ? (installationModel && parseInt(installationModel, 10) > 0 + ? buildSodistoreProPreset(parseInt(installationModel, 10)) + : null) + : (getPresetsForDevice(device)[installationModel] || null); + const inverterCount = presetConfig?.length ?? 1; + + // Default battery limit per cluster: 95A per battery for both charge and discharge + // (so 1-battery cluster → 95A, 2-battery cluster → 190A). + const DEFAULT_CURRENT_PER_BATTERY = 95; + const defaultClusterCurrent = (batteryCount: number) => batteryCount * DEFAULT_CURRENT_PER_BATTERY; + + // (No standalone preset-based builder — overlayTopology() handles the empty case + // and seeds defaults using the actual installed battery count from the Information tab, + // not the preset slot count.) + + // Helper to build form values from S3 data. + // V2 reads only fields it actually consumes — legacy flat keys (InverterNumber, + // BatteriesCount, MaximumChargingCurrent, etc.) are no longer wired through. + const getS3Values = (): Partial => { + // Read per-inverter Clusters/PvCount from each Devices.InverterN entry on disk. + const cfgDevices = (props.values.Config as any).Devices as { [k: string]: any } | undefined; + const cfgFromDisk: { [k: string]: InverterConfig } | undefined = cfgDevices + ? Object.fromEntries( + Object.entries(cfgDevices) + .filter(([k, v]: [string, any]) => k.startsWith('Inverter') && (v?.Clusters || v?.PvCount != null)) + .map(([k, v]: [string, any]) => [k, { Clusters: v.Clusters ?? {}, PvCount: v.PvCount ?? 0 }]) + ) + : undefined; + const hasDevicesData = cfgFromDisk && Object.keys(cfgFromDisk).length > 0; + return { + minimumSoC: props.values.Config.MinSoc, + // Information tab is source of truth for topology + per-cluster current defaults. + devices: overlayTopology(hasDevicesData ? cfgFromDisk : undefined), + operatingPriority: resolveOperatingPriorityIndex( + props.values.Config.OperatingPriority + ), + timeChargeandDischargePower: props.values.Config?.TimeChargeandDischargePower ?? 0, + startTimeChargeandDischargeDayandTime: (() => { + const raw = props.values.Config?.StartTimeChargeandDischargeDayandTime; + const parsed = raw ? dayjs(raw) : null; + return parsed && parsed.year() >= 2020 ? parsed.toDate() : new Date(); + })(), + stopTimeChargeandDischargeDayandTime: (() => { + const raw = props.values.Config?.StopTimeChargeandDischargeDayandTime; + const parsed = raw ? dayjs(raw) : null; + return parsed && parsed.year() >= 2020 ? parsed.toDate() : new Date(); + })(), + controlPermission: String(props.values.Config.ControlPermission).toLowerCase() === "true", + dynamicPricingMode: (props.values.Config as any).DynamicPricingMode ?? 'Disabled', + currentPrice: (props.values.Config as any).CurrentPrice?.toString() ?? '', + priceToSell: (props.values.Config as any).PriceToSell?.toString() ?? '', + priceToBuy: (props.values.Config as any).PriceToBuy?.toString() ?? '', + timeToSellFrom: (props.values.Config as any).TimeToSellFrom ?? '', + timeToSellTo: (props.values.Config as any).TimeToSellTo ?? '', + timeToBuyFrom: (props.values.Config as any).TimeToBuyFrom ?? '', + timeToBuyTo: (props.values.Config as any).TimeToBuyTo ?? '', + }; + }; + + // Restore pending config from localStorage, converting date strings back to Date objects. + // Returns { values, s3ConfigSnapshot } or null if no pending config. + const restorePendingConfig = () => { + try { + const pendingStr = localStorage.getItem(pendingConfigKey); + if (!pendingStr) return null; + + const pending = JSON.parse(pendingStr); + const v = pending.values; + const values: Partial = { + ...v, + // JSON.stringify converts Date→string; restore them back to Date objects + startTimeChargeandDischargeDayandTime: + v.startTimeChargeandDischargeDayandTime + ? dayjs(v.startTimeChargeandDischargeDayandTime).toDate() + : null, + stopTimeChargeandDischargeDayandTime: + v.stopTimeChargeandDischargeDayandTime + ? dayjs(v.stopTimeChargeandDischargeDayandTime).toDate() + : null, + }; + + return { values, s3ConfigSnapshot: pending.s3ConfigSnapshot || null }; + } catch (e) { + console.error('[Config:restore] Failed to parse localStorage', e); + localStorage.removeItem(pendingConfigKey); + return null; + } + }; + + // Fingerprint S3 Config for change detection (not value comparison) + const getS3ConfigFingerprint = () => JSON.stringify(props.values.Config); + + // Overlay Information-tab-derived topology onto a `devices` config object. + // Battery counts come from the SN tree (filled SNs); PvCount comes from pvStringsPerInverter. + // Existing per-cluster current limits are preserved. + const overlayTopology = ( + devices: { [k: string]: InverterConfig } | undefined + ): { [k: string]: InverterConfig } | undefined => { + if (!presetConfig) return devices; + const tree = parseBatterySnTree(props.installation.batterySerialNumbers || '', presetConfig); + const pvStrings = (props.installation.pvStringsPerInverter || '') + .split(',') + .map((s) => s.trim()); + const out: { [k: string]: InverterConfig } = {}; + presetConfig.forEach((clusters, invIdx) => { + const invKey = `Inverter${invIdx + 1}`; + const existingInv = devices?.[invKey]; + const cls: { [k: string]: any } = {}; + clusters.forEach((slotCount, clIdx) => { + const clKey = `Cluster${clIdx + 1}`; + const filled = (tree[invIdx]?.[clIdx] ?? []).filter((s) => s !== '').length; + const existingCl = existingInv?.Clusters?.[clKey]; + // Default current uses the cluster's ideal battery count (slotCount from the + // installation model preset), not the count of filled SNs — so an empty or + // partially-filled cluster still ships a sane non-zero limit. + const defaultCurrent = defaultClusterCurrent(slotCount); + cls[clKey] = { + BatteryCount: filled, + MaxChargingCurrent: existingCl?.MaxChargingCurrent ?? defaultCurrent, + MaxDischargingCurrent: existingCl?.MaxDischargingCurrent ?? defaultCurrent, + }; + }); + out[invKey] = { + Clusters: cls, + PvCount: parseInt(pvStrings[invIdx] || '0', 10) || 0, + }; + }); + return out; + }; + + // Initialize form from localStorage (if pending submit exists) or from S3 + // This runs in the useState initializer so the component never renders stale values + const [formValues, setFormValues] = useState>(() => { + const pending = restorePendingConfig(); + const s3 = getS3Values(); + if (pending) { + // Check if S3 has new data since submit (fingerprint changed from snapshot) + const currentFingerprint = getS3ConfigFingerprint(); + const s3Changed = pending.s3ConfigSnapshot && currentFingerprint !== pending.s3ConfigSnapshot; + + if (s3Changed) { + // Device uploaded new data since our submit — trust S3 (device is authority) + localStorage.removeItem(pendingConfigKey); + return s3; + } + + // S3 still has same data as when we submitted — show pending values + return pending.values; + } + return s3; + }); + + // When S3 data updates (polled every 60s), reconcile with any pending localStorage. + // Strategy: device is the authority. Once S3 Config changes from the snapshot taken at + // submit time, the device has uploaded new data — trust S3 regardless of values. + // Skip reset if the user is actively editing (formDirty). + useEffect(() => { + if (formDirty) return; + + const s3Values = getS3Values(); + const pending = restorePendingConfig(); + + if (pending) { + const currentFingerprint = getS3ConfigFingerprint(); + const s3Changed = pending.s3ConfigSnapshot && currentFingerprint !== pending.s3ConfigSnapshot; + if (s3Changed) { + // S3 Config changed from snapshot → device uploaded new data → trust S3 + localStorage.removeItem(pendingConfigKey); + setFormValues(s3Values); + } else { + // S3 still has same data as at submit time — keep showing pending values + setFormValues(pending.values); + } + return; + } + + // No pending config — trust S3 (source of truth) + setFormValues(s3Values); + }, [props.values]); + + const handleOperatingPriorityChange = (event) => { + setFormDirty(true); + setFormValues({ + ...formValues, + ['operatingPriority']: OperatingPriorityOptions.indexOf( + event.target.value + ) + }); + }; + +// Add time validation function — only relevant for Sinexcel BatteryPriority + const validateTimeOnly = () => { + if (device === 4 && + OperatingPriorityOptions[formValues.operatingPriority] === 'BatteryPriority' && + formValues.startTimeChargeandDischargeDayandTime && + formValues.stopTimeChargeandDischargeDayandTime) { + const startHours = formValues.startTimeChargeandDischargeDayandTime.getHours(); + const startMinutes = formValues.startTimeChargeandDischargeDayandTime.getMinutes(); + const stopHours = formValues.stopTimeChargeandDischargeDayandTime.getHours(); + const stopMinutes = formValues.stopTimeChargeandDischargeDayandTime.getMinutes(); + + const startTimeInMinutes = startHours * 60 + startMinutes; + const stopTimeInMinutes = stopHours * 60 + stopMinutes; + + if (startTimeInMinutes >= stopTimeInMinutes) { + setDateSelectionError(intl.formatMessage({ id: 'stopTimeMustBeLater' })); + setErrorDateModalOpen(true); + return false; + } + } + return true; + }; + + const handleSubmit = async (e) => { + if (!validateTimeOnly()) { + return; + } + // Re-overlay Information-tab topology at submit time, so battery counts and PV count + // are always the latest from the Information tab (it's the source of truth). + const devices = overlayTopology(formValues.devices); + const configurationToSend: Partial = { + minimumSoC: formValues.minimumSoC, + devices, + operatingPriority: formValues.operatingPriority, + timeChargeandDischargePower: formValues.timeChargeandDischargePower, + startTimeChargeandDischargeDayandTime: formValues.startTimeChargeandDischargeDayandTime + ? new Date(formValues.startTimeChargeandDischargeDayandTime.getTime() - formValues.startTimeChargeandDischargeDayandTime.getTimezoneOffset() * 60000) + : null, + stopTimeChargeandDischargeDayandTime: formValues.stopTimeChargeandDischargeDayandTime + ? new Date(formValues.stopTimeChargeandDischargeDayandTime.getTime() - formValues.stopTimeChargeandDischargeDayandTime.getTimezoneOffset() * 60000) + : null, + controlPermission:formValues.controlPermission, + dynamicPricingMode: formValues.dynamicPricingMode, + currentPrice: formValues.currentPrice, + priceToSell: formValues.priceToSell, + priceToBuy: formValues.priceToBuy, + timeToSellFrom: formValues.timeToSellFrom, + timeToSellTo: formValues.timeToSellTo, + timeToBuyFrom: formValues.timeToBuyFrom, + timeToBuyTo: formValues.timeToBuyTo, + }; + + setLoading(true); + const res = await axiosConfig + .post( + `/EditInstallationConfig?installationId=${props.id}&product=${product}`, + configurationToSend + ) + .catch((err) => { + if (err.response) { + setError(true); + setLoading(false); + } + }); + + if (res) { + setUpdated(true); + setLoading(false); + setFormDirty(false); + + // Save submitted values + S3 snapshot to localStorage for optimistic UI update. + // s3ConfigSnapshot = fingerprint of S3 Config at submit time. + // When S3 Config changes from this snapshot, the device has uploaded new data. + const cachePayload = { + values: formValues, + submittedAt: Date.now(), + s3ConfigSnapshot: getS3ConfigFingerprint(), + }; + localStorage.setItem(pendingConfigKey, JSON.stringify(cachePayload)); + } + }; + + const handleChange = (e) => { + setFormDirty(true); + const { name, value } = e.target; + + if (name === 'minimumSoC') { + const numValue = parseFloat(value); + + // invalid characters or not a number + if (/[^0-9.]/.test(value) || isNaN(numValue)) { + SetErrorForField(name, 'Invalid number format'); + } else { + const minsocRanges = { + 3: { min: 10, max: 30 }, + 4: { min: 5, max: 100 }, + }; + + const { min, max } = minsocRanges[device] || { min: 10, max: 30 }; + + if (numValue < min || numValue > max) { + SetErrorForField(name, `Value should be between ${min}-${max}%`); + } else { + // ✅ valid → clear error + SetErrorForField(name, ''); + } + } + } + + setFormValues(prev => ({ + ...prev, + [name]: value, + })); + }; + + const handleTimeChargeDischargeChange = (name: string, value: any) => { + setFormDirty(true); + setFormValues((prev) => ({ + ...prev, + [name]: value + })); + }; + + const handleOkOnErrorDateModal = () => { + setErrorDateModalOpen(false); + }; + + return ( + + + {isErrorDateModalOpen && ( + {}}> + + + {dateSelectionError} + + + + + + )} + + + + + <> +
+ { + setFormDirty(true); + setFormValues((prev) => ({ + ...prev, + controlPermission: e.target.checked, + })); + } + } + sx={{ transform: "scale(1.4)", marginLeft: "15px" }} + /> + } + sx={{ ml: 0 }} + label={ + + } + /> +
+ + {(device === 3 || device === 4) && ( + <> + + + + + + )} + +
+ {/**/} + {/* }*/} + {/* name="minimumSoC"*/} + {/* value={formValues.minimumSoC}*/} + {/* onChange={handleChange}*/} + {/* helperText={*/} + {/* errors.minimumSoC ? (*/} + {/* */} + {/* Value should be between {device === 4 ? '5–100' : '10–30'}%*/} + {/* */} + {/* ) : (*/} + {/* ''*/} + {/* )*/} + {/* }*/} + {/* fullWidth*/} + {/*/>*/} + + +
+ + {(device === 3 || device === 4) ? ( + // Per-cluster, per-inverter charging/discharging current limits — nested config. + Array.from({ length: inverterCount }, (_, invIdx) => { + const invKey = `Inverter${invIdx + 1}`; + const clusters = presetConfig?.[invIdx] ?? [0]; + return ( + + } + sx={{ + '& .MuiAccordionSummary-content': { flexGrow: 0, justifyContent: 'flex-start' }, + justifyContent: 'flex-start', + '& .MuiAccordionSummary-expandIconWrapper': { ml: 1 } + }} + > + + + + + + {clusters.map((_slotCount, clIdx) => { + const clKey = `Cluster${clIdx + 1}`; + const cluster = formValues.devices?.[invKey]?.Clusters?.[clKey]; + const charge = cluster?.MaxChargingCurrent ?? ''; + const discharge = cluster?.MaxDischargingCurrent ?? ''; + const setClusterField = ( + field: 'MaxChargingCurrent' | 'MaxDischargingCurrent', + v: string + ) => { + if (v !== '' && !/^\d*\.?\d*$/.test(v)) return; + setFormDirty(true); + setFormValues((prev) => { + const devices = { ...(prev.devices ?? {}) }; + const inv = devices[invKey] + ?? { Clusters: {}, PvCount: 0 }; + const cls = { ...(inv.Clusters ?? {}) }; + const existing = cls[clKey] ?? { + BatteryCount: presetConfig?.[invIdx]?.[clIdx] ?? 0, + MaxChargingCurrent: 0, + MaxDischargingCurrent: 0, + }; + if (v === '') { + // Drop the field while editing so the input renders empty, + // not "0". On submit, anything still missing falls back to 0. + const next: any = { ...existing }; + delete next[field]; + cls[clKey] = next; + } else { + cls[clKey] = { ...existing, [field]: parseFloat(v) }; + } + devices[invKey] = { ...inv, Clusters: cls }; + return { ...prev, devices }; + }); + }; + return ( +
+ + + + setClusterField('MaxChargingCurrent', e.target.value)} + fullWidth + /> + setClusterField('MaxDischargingCurrent', e.target.value)} + fullWidth + /> +
+ ); + })} +
+
+ ); + }) + ) : ( + <> +
+ +
+ +
+ +
+ + )} + + {(device === 3 || device === 4) && ( + <> + + + + + + )} + +
+ + + + + + +
+ + + {/* --- Sinexcel + BatteryPriority (maps to TimeChargeDischarge on device) --- */} + {device === 4 && + OperatingPriorityOptions[formValues.operatingPriority] === + 'BatteryPriority' && ( + <> + {/* Power input*/} +
+ + handleTimeChargeDischargeChange(e.target.name, e.target.value) + } + helperText={intl.formatMessage({ id: 'perInverter' })} + fullWidth + /> +
+ + {/* Start DateTime */} +
+ + + setFormValues((prev) => ({ + ...prev, + startTimeChargeandDischargeDayandTime: newValue + ? newValue.toDate() + : null, + })) + } + renderInput={(params) => ( + + )} + /> + +
+ + {/* Stop DateTime */} +
+ + + setFormValues((prev) => ({ + ...prev, + stopTimeChargeandDischargeDayandTime: newValue + ? newValue.toDate() + : null, + })) + } + renderInput={(params) => ( + + )} + /> + +
+ + )} + + {/* --- Growatt + Sinexcel under LoadPriority: Dynamic Pricing --- */} + {(device === 3 || device === 4) && + OperatingPriorityOptions[formValues.operatingPriority] === 'LoadPriority' && ( + <> + + + + + +
+ + + + + + +
+ + {formValues.dynamicPricingMode === 'Tou' && ( + <> + {(() => { + const renderTimeField = ( + labelId: string, + key: 'timeToSellFrom' | 'timeToSellTo' | 'timeToBuyFrom' | 'timeToBuyTo' + ) => { + const raw = formValues[key]; + const parsed = raw ? dayjs(raw, 'HH:mm') : null; + return ( + + { + setFormDirty(true); + setFormValues((prev) => ({ + ...prev, + [key]: newValue ? newValue.format('HH:mm') : '', + })); + }} + renderInput={(params) => ( + + )} + /> + + ); + }; + + return ( + <> + + + +
+ {renderTimeField('timeFrom', 'timeToSellFrom')} + {renderTimeField('timeTo', 'timeToSellTo')} +
+ + + + +
+ {renderTimeField('timeFrom', 'timeToBuyFrom')} + {renderTimeField('timeTo', 'timeToBuyTo')} +
+ + ); + })()} + + )} + + {formValues.dynamicPricingMode === 'SpotPrice' && ( + <> +
+ +
+ +
+ CHF/kWh, + }} + fullWidth + /> +
+ +
+ { + const v = e.target.value; + if (v === '' || /^\d*\.?\d*$/.test(v)) { + setFormDirty(true); + setFormValues((prev) => ({ ...prev, priceToSell: v })); + } + }} + InputProps={{ + endAdornment: CHF/kWh, + }} + fullWidth + /> +
+ +
+ { + const v = e.target.value; + if (v === '' || /^\d*\.?\d*$/.test(v)) { + setFormDirty(true); + setFormValues((prev) => ({ ...prev, priceToBuy: v })); + } + }} + InputProps={{ + endAdornment: CHF/kWh, + }} + fullWidth + /> +
+ + )} + + )} + +
+ + {loading && ( + + )} + + {updated && ( + + + setUpdated(false)} + sx={{ marginLeft: '4px' }} + > + + + + )} + {error && ( + + + setError(false)} + sx={{ marginLeft: '4px' }} + > + + + + )} +
+
+
+
+
+
+ ); +} + +export default SodistoreHomeConfigurationV2;