All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/PropertyPanel Properties.tsx

64.91% Statements 148/228
63.78% Branches 118/185
53.33% Functions 24/45
80% Lines 116/145

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                    76x                             76x                     15218x         22408x   15218x 15218x 15218x   15218x   15218x 15218x 15218x 15218x     275x 275x                         11x           11x 31x     11x         11x 11x                           286x       285x               1x         43402x         9240x           22715x   79729x         52x     249x                         5x       39x                                 1749x   1749x 1749x   1749x   11180x                 7357x   1749x   22360x     2129x   1749x 11180x   1749x 11180x       1749x     332x             10848x                         8745x                           851x   565x     286x 286x 190x   177x     286x     1992x 2809x       1992x       1992x 265x 1992x 1992x 2522x 201x 1992x 2193x         434x 434x           4x   4x 2426x 1992x         1992x     1992x   2256x 1736x           5250x     4914x                 2845x     2845x 2845x     2845x 2845x 851x     7x   844x   9227x     1636x     851x     851x 565x     286x   286x           190x       286x       851x 851x           286x                   851x 4694x   851x   2845x 4914x 19331x       718x     718x       4999x       4281x   1689x               7912x 2126x                                               17727x 402x         3649x 9184x 9187x      
import { toast } from "sonner";
import {
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/ahuora-design-system/ui/accordion";
import {
  api,
  Finding,
  MonitoringTableRead,
  ObjectTypeEnum,
  PropertyInfoRead,
  PropertySetRead,
  PropertyValueRead,
  useCorePropertyinfoPartialUpdateMutation,
  useCorePropertyvaluePartialUpdateMutation,
  useDiagnosticsEvaluateSimulationObjectPropertyRulesQuery,
} from "@/api/apiStore.gen";
import { ObjectType, PropertySetType } from "@/data/ObjectTypes.gen";
import objs from "@/data/objects.json";
import { useCurrentObject } from "@/hooks/flowsheetObjects";
import { isStream } from "@/lib/isStream";
import { useAppDispatch } from "@/store/hooks";
import { infoMessages } from "../../InfoData";
import { MLProperties } from "../../LeftSideBar/Formulas/MLProperties";
import type { RuleFinding } from "../Diagnostics/useRuleValidation";
import { CompoundListSection } from "./CompoundList";
import { isEconomicsProperty } from "./economicsPropertyMetadata";
import { IndexedVariableWithUnit } from "./InputFields/IndexedVariableWithUnit";
import { PropertyCheckbox } from "./InputFields/PropertyCheckbox";
import { PropertyDropdown } from "./InputFields/PropertyDropdown";
import { PropertyTextField } from "./InputFields/PropertyTextField";
import { PropertiesStatus } from "./PropertiesStatus";
 
const objects = objs as Record<string, ObjectType>;
interface PropertyProps {
  property: PropertyInfoRead;
  isOperatingVariable?: boolean;
  withMSSConnection?: boolean;
  deletePropertyFunction?: (property_val_key: string) => void;
  ruleFindingsByPropertyKey?: Record<string, RuleFinding[]>;
  monitoringTables?: MonitoringTableRead[];
}
 
type MutationResult = ReturnType<
  typeof useCorePropertyinfoPartialUpdateMutation
>[0];
 
// Convert backend Finding to UI RuleFinding format for frontend display give it an id etc
const toRuleFinding = (finding: Finding): RuleFinding => ({
  id:
    finding.id ??
    `${finding.ruleReference ?? "finding"}-${finding.propertyId ?? "property"}-${finding.title}`,
  severity: finding.severity,
  title: finding.title,
  description: finding.description,
  ruleReference: finding.ruleReference ?? undefined,
  propertyKey: finding.propertyKey ?? undefined,
});
 
export function Property({
  property,
  withMSSConnection,
  deletePropertyFunction,
  ruleFindingsByPropertyKey,
  monitoringTables = [],
}: PropertyProps) {
  const [updateValue] = useCorePropertyvaluePartialUpdateMutation();
  const [updateProperty] = useCorePropertyinfoPartialUpdateMutation();
  const currentObject = useCurrentObject();
  const printToast = true; // TODO: Make this a prop
  const dispatch = useAppDispatch();
 
  const currentObjectType = currentObject?.objectType;
  const currentObjectId = currentObject?.id;
  const objectSchema = objects[currentObjectType];
  const propertySchema = objectSchema?.properties[property.key];
 
  const onUpdateIndexedValue = (value: string, id: number) => {
    updateBackendWithToast(() => {
      return updateValue({
        id,
        patchedPropertyValue: {
          value,
        },
      });
    }, value);
  };
 
  const onUpdateUnit = (unit: string) => {
    Iif (!currentObjectId) return;
 
    // Optimistically update the property
    dispatch(
      api.util.updateQueryData(
        "unitopsSimulationobjectsRetrieve",
        { id: currentObjectId },
        (cachedSimulationObject) => {
          const cachedProperty =
            cachedSimulationObject.properties.ContainedProperties.find(
              (prop) => prop.id === property.id,
            );
          if (cachedProperty) {
            cachedProperty.unit = unit;
          }
        },
      ),
    );
    updateBackendWithToast(() => {
      return updateProperty({
        id: property.id,
        patchedPropertyInfo: {
          unit: unit,
        },
      });
    }, unit);
  };
 
  const updateBackendWithToast = (
    fn: () => ReturnType<MutationResult>,
    updatedValue: string | number | boolean,
  ) => {
    // Update the backend
    fn()
      .unwrap()
      .then(() => {
        if (printToast) {
          toast.success(
            `Successfully updated ${property.displayName} to ${updatedValue}`,
          );
        }
        return;
      })
      .catch((error) => {
        // TODO: Add error handling in future to correctly display this error
        console.error(
          `Failed to update ${property.displayName} to ${updatedValue}: ${error.data.error}`,
        );
        return;
      });
  };
  switch (property.type) {
    case "numeric_arg":
    case "numeric": {
      return (
        <IndexedVariableWithUnit
          property={property}
          onUpdateValue={onUpdateIndexedValue}
          onUpdateUnit={onUpdateUnit}
          withMSSConnection={withMSSConnection}
          deletePropertyFunction={deletePropertyFunction}
          ruleFindings={ruleFindingsByPropertyKey?.[property.key] ?? []}
          monitoringTables={monitoringTables}
        />
      );
    }
    case "checkbox": {
      return (
        <PropertyCheckbox
          property={property}
          onUpdateValue={onUpdateIndexedValue}
        />
      );
    }
    case "text": {
      return (
        <PropertyTextField
          property={property}
          onUpdateValue={onUpdateIndexedValue}
        />
      );
    }
    case "dropdown": {
      return (
        <PropertyDropdown
          property={property}
          onUpdateValue={onUpdateIndexedValue}
          schema={propertySchema}
        ></PropertyDropdown>
      );
    }
    default: {
      return <>Default Type</>;
    }
  }
}
 
export interface OrderedPropertyListProps {
  properties: PropertyInfoRead[];
  schema: PropertySetType;
  deletePropertyFunction?: (property_val_key: string) => void;
  ruleFindingsByPropertyKey?: Record<string, RuleFinding[]>;
  monitoringTables?: MonitoringTableRead[];
}
 
export function OrderedPropertyList(props: OrderedPropertyListProps) {
  // With no calculation modes, we don't really want to order the property list, other than splitting out operating variables and reactive properties.
  const isComposition = props.schema.type === "composition" ? true : false;
  const withMSSConnection = props.schema.type === "composition" ? false : true;
 
  const mapFn = (property, index) => {
    return (
      <Property
        key={index}
        property={property}
        withMSSConnection={withMSSConnection}
        deletePropertyFunction={props.deletePropertyFunction}
        ruleFindingsByPropertyKey={props.ruleFindingsByPropertyKey}
        monitoringTables={props.monitoringTables}
      />
    );
  };
 
  const isOperatingVariable = (prop: PropertyValueRead) => {
    return (
      prop.controlManipulated !== null ||
      (props.schema && props.schema.stateVars?.includes(prop.key))
    );
  };
 
  const operatingVariables = props.properties.filter((prop) =>
    isOperatingVariable(prop),
  );
  const reactiveProperties = props.properties.filter(
    (prop) => !isOperatingVariable(prop),
  );
 
  return (
    <div className=" mx-4">
      {isComposition ? (
        <div className="mt-2">
          {operatingVariables.map((property, index) => mapFn(property, index))}
        </div>
      ) : (
        <div className="flex flex-col gap-4">
          <div className="flex flex-col gap-2">
            <div className="gap-2">
              {operatingVariables.map((property, index) =>
                mapFn(property, index),
              )}
            </div>
          </div>
          <div className="flex flex-col gap-1">
            <div>
              {reactiveProperties.map((property, index) =>
                mapFn(property, index),
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
 
export type PropertySetComponentProps = {
  schema: PropertySetType;
  properties: PropertyInfoRead[];
  propertySet: PropertySetRead;
};
 
function manageCompoundDisplay(
  isStream: boolean,
  compositionData: PropertyInfoRead | undefined,
) {
  const compounds: PropertyValueRead | undefined = compositionData?.values;
  if (!compounds || !isStream) {
    return infoMessages.error;
  }
 
  let total: number = 0;
  Object?.keys(compounds).forEach((key) => {
    const compValue = compounds[key]?.value;
    if (compValue || compValue != undefined) {
      total += +compValue;
    }
  });
  return total === 1 ? infoMessages.success : infoMessages.error;
}
 
export function Properties({
  monitoringTables = [],
}: {
  monitoringTables?: MonitoringTableRead[];
}) {
  const currentObj = useCurrentObject();
  // Important: one diagnostics subscription per object panel.
  // This avoids per-field request fan-out (which can cause flaky timing in UI tests).
  const { data: objectRuleFindings } =
    useDiagnosticsEvaluateSimulationObjectPropertyRulesQuery(
      {
        flowsheet: currentObj?.flowsheet ?? 0,
        simulationObjectId: currentObj?.id ?? 0,
      },
      {
        skip: !currentObj?.id || !currentObj?.flowsheet,
      },
    );
 
  const ruleFindingsByPropertyKey = (() => {
    // We group once here, then each property row reads only its own findings.
    const groupedFindings: Record<string, RuleFinding[]> = {};
    objectRuleFindings?.findings?.forEach((finding) => {
      if (!finding.propertyKey) {
        // Object-level findings (no propertyKey) are not shown inline on a field.
        return;
      }
      if (!groupedFindings[finding.propertyKey]) {
        groupedFindings[finding.propertyKey] = [];
      }
      groupedFindings[finding.propertyKey].push(toRuleFinding(finding));
    });
    return groupedFindings;
  })();
 
  Iif (!currentObj) return null;
 
  const objectSchema = objects[currentObj.objectType!];
  Iif (!objectSchema?.propertySetGroups) return null;
 
  const propertySetGroups = objectSchema.propertySetGroups!;
 
  return Object.keys(propertySetGroups).map((groupKey) => (
    <PropertySetGroup
      key={groupKey}
      groupKey={groupKey}
      ruleFindingsByPropertyKey={ruleFindingsByPropertyKey}
      monitoringTables={monitoringTables}
    />
  ));
}
 
function PropertySetGroup({
  groupKey,
  ruleFindingsByPropertyKey,
  monitoringTables,
}: {
  groupKey: string;
  ruleFindingsByPropertyKey: Record<string, RuleFinding[]>;
  monitoringTables: MonitoringTableRead[];
}) {
  const currentObj = useCurrentObject();
  Iif (!currentObj) return null;
 
  const propertySet = currentObj.properties;
  const objectSchema = objects[currentObj.objectType!];
  Iif (!objectSchema?.propertySetGroups) return null;
 
  const propertySetGroups = objectSchema.propertySetGroups!;
  const schema = propertySetGroups[groupKey];
  const propertyInfos = (() => {
    // guard against objects without schema properties e.g. group and machineLearningBlock
    if (Object.keys(objectSchema?.properties ?? {}).length === 0) {
      return [];
    }
    return propertySet.ContainedProperties.filter((prop) => {
      return (
        objectSchema?.properties[prop.key]?.propertySetGroup == groupKey &&
        !isEconomicsProperty(prop)
      );
    });
  })();
 
  const moleFracComp = propertyInfos.find((p) => p.key === "mole_frac_comp");
  // Convert compound values to a simpler format for validation.
  // Only process data when viewing the composition tab.
  const compoundValues = (() => {
    Iif (groupKey !== "composition" || !moleFracComp?.values) return undefined;
 
    // convert to the format expected by PropertiesStatus
    const result: { [key: string]: { value: string | number } } = {};
 
    Object.entries(moleFracComp.values).forEach(([key, valueObj]) => {
      // skip the id property and any non-object values
      Iif (key === "id" || !valueObj || typeof valueObj !== "object") return;
 
      // only include if it has a value property
      if ("value" in valueObj) {
        result[key] = { value: valueObj.value };
      }
    });
 
    return result;
  })();
 
  // Showing property set status
  let statusInfo = propertySet.unspecifiedProperties;
  const compInfo = manageCompoundDisplay(
    isStream(currentObj),
    propertyInfos.find((property) => property.key === "mole_frac_comp"),
  );
 
  if (groupKey === "composition" && isStream(currentObj)) {
    statusInfo = compInfo === infoMessages.success ? [] : ["mole_frac_comp"];
  }
  if (compInfo === infoMessages.success && groupKey !== "composition") {
    // Remove "Compounds" if compInfo is success
    statusInfo = propertySet.unspecifiedProperties?.filter(
      (prop) => prop !== "Compounds" && prop !== "mole_frac_comp",
    );
  }
 
  // Enable/Disable additional properties
  const toggleProperty = propertyInfos.find(
    (prop) => prop.key === schema.toggle,
  );
  const toggleEnabled =
    !toggleProperty || toggleProperty?.values[0].value == true; // there is only one propertyValue for a toggle property
  const otherProperties = propertyInfos.filter(
    (prop) => prop.key !== schema.toggle,
  );
 
  return (
    <AccordionItem value={groupKey}>
      <AccordionTrigger
        variant="default"
        statusIcon={
          <PropertiesStatus
            propertySet={statusInfo}
            propertySetGroup={groupKey}
            compoundValues={compoundValues}
          />
        }
      >
        {schema.displayName}
      </AccordionTrigger>
      <AccordionContent className="p-0">
        {toggleProperty && (
          <div className="p-2">
            <Property
              property={toggleProperty}
              ruleFindingsByPropertyKey={ruleFindingsByPropertyKey}
              monitoringTables={monitoringTables}
            />
          </div>
        )}
        {toggleEnabled &&
          (schema.type === "composition" ? (
            <CompoundListSection
              schema={schema}
              properties={otherProperties}
              propertySet={propertySet}
              // Composition uses a different rendering path, so we forward
              // findings explicitly to keep mole-fraction inline messages working.
              ruleFindingsByPropertyKey={ruleFindingsByPropertyKey}
              monitoringTables={monitoringTables}
            />
          ) : currentObj!.objectType! === "specificationBlock" ? (
            <SpecificationBlockProperties
              schema={schema}
              properties={otherProperties}
              propertySet={propertySet}
            />
          ) : (
            <OrderedPropertyList
              properties={otherProperties}
              schema={schema}
              ruleFindingsByPropertyKey={ruleFindingsByPropertyKey}
              monitoringTables={monitoringTables}
            />
          ))}
        {currentObj?.objectType === ObjectTypeEnum.MachineLearningBlock &&
          groupKey === "default" && (
            <div className="mx-4">
              <MLProperties />
            </div>
          )}
      </AccordionContent>
    </AccordionItem>
  );
}