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

93.57% Statements 102/109
73.97% Branches 54/73
94.28% Functions 33/35
94.28% Lines 99/105

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                                                              49x                           49x                                 12680x 12680x 12680x 12680x 12680x   12680x 12680x 12680x   12680x 216x 216x                 12680x   11x           11x 31x   11x 11x         11x 11x                 12680x         227x     219x 219x       219x       2x     2x     12680x     12127x                       527x                               26x                                             1932x 1932x   1932x 12350x                     1932x 24700x             1932x 12350x   1932x 12350x     1932x       390x             11960x                                                     2335x 2335x 1605x     730x 730x 405x 405x 374x     730x       1446x       1446x                   1446x   376x 376x 3x       3x 3x   3x   376x     1446x 1446x   1446x 2335x                             2335x 2335x 2335x 2335x 2335x 2335x 672x 667x 7364x           5x     13355x       2335x 332x     156x   156x   95x     95x 95x       156x       2335x 2335x   13355x     2335x 730x   2335x               2335x 12634x     2335x 2335x 13355x     2335x                                                                                                    
import React, { useMemo } from "react";
import { toast } from "sonner";
import {
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/ahuora-design-system/ui/accordion";
import {
  api,
  Finding,
  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 type { RuleFinding } from "../Diagnostics/useRuleValidation";
import { CompoundListSection } from "./CompoundList";
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[]>;
}
 
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,
}: 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 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) => {
    // Optimistically update the property
    dispatch(
      api.util.updateQueryData(
        "unitopsSimulationobjectsRetrieve",
        { id: currentObject!.id },
        (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] ?? []}
        />
      );
    }
    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[]>;
}
 
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}
      />
    );
  };
 
  const isOperatingVariable = (prop: PropertyValueRead) => {
    return (
      prop.controlManipulated !== null ||
      props.schema.stateVars?.includes(prop.key)
      // && prop.controlSetPoint === null
    );
  };
 
  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() {
  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 = useMemo(() => {
    // We group once here, then each property row reads only its own findings.
    const groupedFindings: Record<string, RuleFinding[]> = {};
    objectRuleFindings?.findings?.forEach((finding) => {
      Iif (!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;
  }, [objectRuleFindings?.findings]);
 
  const objectSchema = objects[currentObj!.objectType!];
  const propertySetGroups = objectSchema.propertySetGroups!;
 
  return Object.keys(propertySetGroups).map((groupKey) => (
    <PropertySetGroup
      key={groupKey}
      groupKey={groupKey}
      ruleFindingsByPropertyKey={ruleFindingsByPropertyKey}
    />
  ));
}
 
function PropertySetGroup({
  groupKey,
  ruleFindingsByPropertyKey,
}: {
  groupKey: string;
  ruleFindingsByPropertyKey: Record<string, RuleFinding[]>;
}) {
  const currentObj = useCurrentObject();
  const propertySet = currentObj!.properties;
  const objectSchema = objects[currentObj!.objectType!];
  const propertySetGroups = objectSchema.propertySetGroups!;
  const schema = propertySetGroups[groupKey];
  const propertyInfos = useMemo(() => {
    if (Object.keys(objectSchema?.properties).length !== 0) {
      return propertySet.ContainedProperties.filter((prop) => {
        return objectSchema?.properties[prop.key]?.propertySetGroup == groupKey;
      });
    }
    // If there are no properties defined in the group schema, it must be something
    // like machineLearning block where there are custom properties
    // TODO: Improve how machineLearningBlock is handled (so that we can still have custom properties as well as the ML properties)
    return propertySet.ContainedProperties;
  }, [groupKey, objectSchema?.properties, propertySet.ContainedProperties]);
 
  const moleFracComp = propertyInfos.find((p) => p.key === "mole_frac_comp");
  // Convert compound values to a simpler format for validation
  //uses useMemo to avoid recalculating when inputs haven't changed
  // only processes data when viewing composition tab
  const compoundValues = useMemo(() => {
    if (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;
  }, [moleFracComp?.values, groupKey]);
 
  // 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"];
  }
  Iif (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}
            />
          </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}
            />
          ) : currentObj!.objectType! === "specificationBlock" ? (
            <SpecificationBlockProperties
              schema={schema}
              properties={otherProperties}
              propertySet={propertySet}
            />
          ) : (
            <OrderedPropertyList
              properties={otherProperties}
              schema={schema}
              ruleFindingsByPropertyKey={ruleFindingsByPropertyKey}
            />
          ))}
      </AccordionContent>
    </AccordionItem>
  );
}