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

65.17% Statements 146/224
64.83% Branches 118/182
55.26% Functions 21/38
80.41% Lines 115/143

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                                                                    103x                           103x                             759x   759x 9222x   759x 4153x 4153x 4153x       20422x         31078x   20422x 20422x 20422x   20422x   20422x 20422x 20422x 20422x     297x 297x                         11x           11x 31x     11x         11x 11x                           308x       308x                         55874x         12825x           29052x   109939x         45x     314x                         5x       49x                                 1995x 1995x   1995x   14507x                 8807x     1995x   1995x     14507x 5985x                           765x   508x     257x 257x 161x   145x     257x     2340x 3435x       2340x       2340x 279x 2340x 2340x 2898x 212x 2340x 2552x         450x 450x           3x   3x 2790x 2340x         2340x     2340x   2618x 2184x           6438x     4912x                 3430x     3430x 3430x     3430x 3430x 765x     6x   759x   9265x     1597x 759x           765x     765x 508x     257x   257x           161x       257x       765x 765x           257x                   765x 4759x   765x   3430x 4912x 21740x       668x     668x       5434x       4766x   2136x               9838x 2477x                                               20769x 425x         4280x 10837x 10843x      
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/unitOpConfigs";
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;
  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 sortPropertiesBySchemaOrder(
  properties: PropertyInfoRead[],
  schemaProperties: ObjectType["properties"] | undefined,
): PropertyInfoRead[] {
  Iif (!schemaProperties) return properties;
 
  const schemaOrder = new Map(
    Object.keys(schemaProperties).map((key, index) => [key, index]),
  );
  return [...properties].sort((left, right) => {
    const leftIndex = schemaOrder.get(left.key) ?? Number.MAX_SAFE_INTEGER;
    const rightIndex = schemaOrder.get(right.key) ?? Number.MAX_SAFE_INTEGER;
    return leftIndex - rightIndex;
  });
}
 
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) {
  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}
      />
    );
  };
 
  return (
    <div
      className={
        props.schema.type === "composition" ? "mx-4 mt-2 pb-2" : "mx-4 pb-2"
      }
    >
      {props.properties.map((property, index) => mapFn(property, index))}
    </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 [];
    }
    const groupProperties = propertySet.ContainedProperties.filter((prop) => {
      return (
        objectSchema?.properties[prop.key]?.propertySetGroup == groupKey &&
        !isEconomicsProperty(prop)
      );
    });
    return sortPropertiesBySchemaOrder(
      groupProperties,
      objectSchema.properties,
    );
  })();
 
  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>
  );
}