All files / src/pages/flowsheet-page/economics/operating-lines-panel/creators OutputPropertyLineCreator.tsx

47.5% Statements 76/160
26.49% Branches 40/151
26.47% Functions 9/34
50% Lines 54/108

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 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510                                                                                                          59x                             59x 59x       59x 59x   59x 59x 59x 59x   59x 59x 62x     59x   5x   59x 62x     59x                                                                     59x               177x   59x 5x 62x   59x                           62x   59x       5x   62x                                                               767x             5x       64x                                                                                                             5x 5x                                                                               20x                                                                     25x                                                                                                                                             1121x 62x 236x       76x             76x               76x 76x 76x                   30x                       59x 59x 59x 7x 7x             59x 7x               25x                     25x 25x         10x                                  
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { Plus } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/ahuora-design-system/ui/button";
import { Checkbox } from "@/ahuora-design-system/ui/checkbox";
import { ScrollBar } from "@/ahuora-design-system/ui/scroll-area";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import { Spinner } from "@/ahuora-design-system/ui/spinner";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/ahuora-design-system/ui/table";
import type {
  OperatingLineFromPropertyRequest,
  OperatingLinesFromPropertiesRequest,
  OperatingStreamPropertyOption,
} from "@/api/apiStore.gen";
import {
  EconomicEffectEnum,
  OperatingLineFromPropertyRequestCategoryEnum,
  OperatingLineFromPropertyRequestOutletStreamDispositionEnum,
  RateTypeEnum,
} from "@/api/apiStore.gen";
import { rateTypeLabel } from "../../default-rates/economicsDefaultRates";
import { mutationErrorMessage, type SaveState } from "../model/types";
import { FormState, SectionHeading } from "../ui/fields";
 
type SuggestedGroup =
  | "utility_consumption"
  | "utility_export"
  | "feedstock"
  | "output";
 
type SelectionState = Record<number, boolean>;
type GroupState = Record<number, SuggestedGroup>;
type DispositionState = Record<
  number,
  OperatingLineFromPropertyRequestOutletStreamDispositionEnum
>;
type EnergyRateType = (typeof ENERGY_RATE_TYPES)[number];
type EnergyRateTypeState = Record<number, EnergyRateType>;
 
export function OutputPropertyLineCreator({
  canEdit,
  options,
  loading,
  error,
  saving,
  onCreate,
}: {
  canEdit: boolean;
  options: OperatingStreamPropertyOption[];
  loading: boolean;
  error: boolean;
  saving: boolean;
  onCreate: (payload: OperatingLinesFromPropertiesRequest) => Promise<void>;
}) {
  const selectedObjectId = selectedObjectIdFromUrl();
  const availableOptions = prioritizeSelectedObjectOptions(
    options.filter((option) => !option.selected_operating_line),
    selectedObjectId,
  );
  const [selectedProperties, setSelectedProperties] = useState<SelectionState>(
    {},
  );
  const [groups, setGroups] = useState<GroupState>({});
  const [dispositions, setDispositions] = useState<DispositionState>({});
  const [energyRateTypes, setEnergyRateTypes] = useState<EnergyRateTypeState>(
    {},
  );
  const [saveState, setSaveState] = useState<SaveState>({ kind: "idle" });
  const selectedOptions = availableOptions.filter(
    (option) => selectedProperties[option.property_info],
  );
  const allOptionsSelected =
    availableOptions.length > 0 &&
    availableOptions.every(
      (option) => selectedProperties[option.property_info],
    );
  const someOptionsSelected = availableOptions.some(
    (option) => selectedProperties[option.property_info],
  );
  const disabled =
    !canEdit ||
    saving ||
    loading ||
    saveState.kind === "saving" ||
    availableOptions.length === 0;
 
  const createSelectedLines = async () => {
    Iif (selectedOptions.length === 0) return;
    const payload: OperatingLinesFromPropertiesRequest = {
      lines: selectedOptions.map((option) => lineRequest(option)),
    };
    setSaveState({
      kind: "saving",
      message: "Creating selected operating lines",
    });
    try {
      await onCreate(payload);
      setSelectedProperties({});
      setSaveState({ kind: "saved", message: "Operating lines created" });
    } catch (createError) {
      if (isUnexpectedServerError(createError)) {
        toast.error("Suggested operating properties could not be added", {
          description:
            "An unexpected server error occurred. Please try again or check the backend logs.",
        });
        setSaveState({ kind: "idle" });
        return;
      }
      setSaveState({
        kind: "error",
        message: mutationErrorMessage(createError),
      });
    }
  };
 
  const setAllSelected = (checked: boolean) => {
    setSelectedProperties((current) => {
      const next = { ...current };
      for (const option of availableOptions) {
        next[option.property_info] = checked;
      }
      return next;
    });
  };
 
  const groupFor = (option: OperatingStreamPropertyOption): SuggestedGroup => {
    return groups[option.property_info] ?? recommendedGroupFor(option);
  };
 
  const dispositionFor = (
    option: OperatingStreamPropertyOption,
  ): OperatingLineFromPropertyRequestOutletStreamDispositionEnum => {
    const savedDisposition = dispositions[option.property_info];
    Iif (savedDisposition) return savedDisposition;
    if (
      option.suggested_disposition ===
        OperatingLineFromPropertyRequestOutletStreamDispositionEnum.Sold ||
      option.suggested_disposition ===
        OperatingLineFromPropertyRequestOutletStreamDispositionEnum.Disposed
    ) {
      return option.suggested_disposition;
    }
    return OperatingLineFromPropertyRequestOutletStreamDispositionEnum.Sold;
  };
 
  const energyRateTypeFor = (
    option: OperatingStreamPropertyOption,
  ): EnergyRateType => {
    return (
      energyRateTypes[option.property_info] ?? recommendedEnergyRateType(option)
    );
  };
 
  const lineRequest = (
    option: OperatingStreamPropertyOption,
  ): OperatingLineFromPropertyRequest => {
    const group = groupFor(option);
    const disposition = dispositionFor(option);
    const isUtilityGroup =
      group === "utility_consumption" || group === "utility_export";
    const category = isUtilityGroup
      ? OperatingLineFromPropertyRequestCategoryEnum.Energy
      : group === "feedstock"
        ? OperatingLineFromPropertyRequestCategoryEnum.Feedstock
        : disposition ===
            OperatingLineFromPropertyRequestOutletStreamDispositionEnum.Sold
          ? OperatingLineFromPropertyRequestCategoryEnum.OutputRevenue
          : OperatingLineFromPropertyRequestCategoryEnum.Disposal;
    return {
      property_info: option.property_info,
      category,
      economic_effect:
        group === "utility_export"
          ? EconomicEffectEnum.Revenue
          : category ===
              OperatingLineFromPropertyRequestCategoryEnum.OutputRevenue
            ? EconomicEffectEnum.Revenue
            : EconomicEffectEnum.Cost,
      outlet_stream_disposition: group === "output" ? disposition : undefined,
      ...(category === OperatingLineFromPropertyRequestCategoryEnum.Energy
        ? { rate_type: energyRateTypeFor(option) }
        : {}),
    };
  };
 
  return (
    <section
      className="mt-4 rounded-md border bg-card p-3"
      aria-label="Suggested operating property lines"
    >
      <SectionHeading
        title="Suggested operating properties"
        count={availableOptions.length}
        help="Select suggested properties from terminal output streams, starting input streams, and unit work, heating duty, or cooling duty properties."
      />
      {loading ? (
        <div className="mt-2 flex items-center gap-2 text-sm text-muted-foreground">
          <Spinner size="small" />
          Loading suggested operating properties
        </div>
      ) : error ? (
        <div
          className="mt-2 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive"
          role="alert"
        >
          Could not load suggested operating properties.
        </div>
      ) : options.length === 0 ? (
        <div className="mt-2 text-sm text-muted-foreground">
          No suggested operating properties are available.
        </div>
      ) : availableOptions.length === 0 ? (
        <div className="mt-2 text-sm text-muted-foreground">
          All suggested operating properties have already been added.
        </div>
      ) : (
        <div className="mt-3 space-y-3">
          <ScrollAreaPrimitive.Root
            type="always"
            className="relative w-full overflow-hidden rounded-md border bg-background"
          >
            <ScrollAreaPrimitive.Viewport className="w-full rounded-[inherit]">
              <Table
                className="min-w-[44rem]"
                aria-label="Suggested operating properties table"
              >
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-10 text-xs">
                      <Checkbox
                        checked={
                          allOptionsSelected ||
                          (someOptionsSelected && "indeterminate")
                        }
                        disabled={disabled}
                        aria-label="Select all suggested operating properties"
                        onCheckedChange={(checked) =>
                          setAllSelected(checked === true)
                        }
                      />
                    </TableHead>
                    <TableHead className="text-xs">Source</TableHead>
                    <TableHead className="text-xs">Property</TableHead>
                    <TableHead className="w-44 text-xs">Group</TableHead>
                    <TableHead className="w-48 text-xs">Treatment</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {availableOptions.map((option) => {
                    const rowLabel = `${option.source_object_name} ${propertyLabel(option)}`;
                    const group = groupFor(option);
                    return (
                      <TableRow key={option.property_info}>
                        <TableCell>
                          <Checkbox
                            checked={Boolean(
                              selectedProperties[option.property_info],
                            )}
                            disabled={disabled}
                            aria-label={`Select suggested operating property ${rowLabel}`}
                            onCheckedChange={(checked) =>
                              setSelectedProperties((current) => ({
                                ...current,
                                [option.property_info]: checked === true,
                              }))
                            }
                          />
                        </TableCell>
                        <TableCell className="text-xs font-medium">
                          {option.source_object_name}
                        </TableCell>
                        <TableCell className="text-xs">
                          {propertyLabel(option)}
                        </TableCell>
                        <TableCell>
                          <Select
                            value={group}
                            disabled={disabled}
                            onValueChange={(value) =>
                              setGroups((current) => ({
                                ...current,
                                [option.property_info]: value as SuggestedGroup,
                              }))
                            }
                          >
                            <SelectTrigger aria-label={`Group for ${rowLabel}`}>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {GROUP_OPTIONS.map((groupOption) => (
                                <SelectItem
                                  key={groupOption.value}
                                  value={groupOption.value}
                                >
                                  {groupOption.label}
                                  {recommendedGroupFor(option) ===
                                  groupOption.value
                                    ? " (Recommended)"
                                    : ""}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell>
                          {group === "utility_consumption" ||
                          group === "utility_export" ? (
                            <Select
                              value={energyRateTypeFor(option)}
                              disabled={disabled}
                              onValueChange={(value) => {
                                Iif (!isEnergyRateType(value)) return;
                                setEnergyRateTypes((current) => ({
                                  ...current,
                                  [option.property_info]: value,
                                }));
                              }}
                            >
                              <SelectTrigger
                                aria-label={`Utility type for ${rowLabel}`}
                              >
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {ENERGY_RATE_TYPES.map((rateType) => (
                                  <SelectItem key={rateType} value={rateType}>
                                    {rateTypeLabel(rateType)}
                                    {recommendedEnergyRateType(option) ===
                                    rateType
                                      ? " (Recommended)"
                                      : ""}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          ) : group === "output" ? (
                            <Select
                              value={dispositionFor(option)}
                              disabled={disabled}
                              onValueChange={(value) =>
                                setDispositions((current) => ({
                                  ...current,
                                  [option.property_info]:
                                    value as OperatingLineFromPropertyRequestOutletStreamDispositionEnum,
                                }))
                              }
                            >
                              <SelectTrigger
                                aria-label={`Treatment for ${rowLabel}`}
                              >
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem
                                  value={
                                    OperatingLineFromPropertyRequestOutletStreamDispositionEnum.Sold
                                  }
                                >
                                  Sold
                                </SelectItem>
                                <SelectItem
                                  value={
                                    OperatingLineFromPropertyRequestOutletStreamDispositionEnum.Disposed
                                  }
                                >
                                  Disposed
                                </SelectItem>
                              </SelectContent>
                            </Select>
                          ) : (
                            <div className="flex h-10 cursor-not-allowed items-center rounded-sm bg-muted/30 px-3 text-sm text-muted-foreground opacity-60">
                              Not applicable
                            </div>
                          )}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </ScrollAreaPrimitive.Viewport>
            <ScrollBar orientation="horizontal" />
            <ScrollAreaPrimitive.Corner />
          </ScrollAreaPrimitive.Root>
          <div className="flex justify-end">
            <Button
              type="button"
              size="sm"
              disabled={disabled || selectedOptions.length === 0}
              onClick={() => void createSelectedLines()}
            >
              <Plus className="mr-1 size-4" />
              Add selected
            </Button>
          </div>
        </div>
      )}
      <FormState state={saveState} />
    </section>
  );
}
 
const GROUP_OPTIONS: { value: SuggestedGroup; label: string }[] = [
  { value: "utility_consumption", label: "Utility consumption" },
  { value: "utility_export", label: "Utility export" },
  { value: "feedstock", label: "Feedstock" },
  { value: "output", label: "Sold output / disposal" },
];
 
const ENERGY_RATE_TYPES = [
  RateTypeEnum.Electricity,
  RateTypeEnum.Steam,
  RateTypeEnum.NaturalGas,
  RateTypeEnum.Diesel,
  RateTypeEnum.FuelOil,
] as const;
 
const UNIT_POWER_WORK_SOURCE_KIND = "unit_power_work_property";
const UNIT_HEATING_DUTY_SOURCE_KIND = "unit_heating_duty_property";
const UNIT_COOLING_DUTY_SOURCE_KIND = "unit_cooling_duty_property";
 
function isEnergyRateType(value: string): value is EnergyRateType {
  return ENERGY_RATE_TYPES.includes(value as EnergyRateType);
}
 
function recommendedEnergyRateType(
  option: OperatingStreamPropertyOption,
): EnergyRateType {
  if (option.source_kind === UNIT_POWER_WORK_SOURCE_KIND) {
    return RateTypeEnum.Electricity;
  }
  if (option.source_kind === UNIT_HEATING_DUTY_SOURCE_KIND) {
    return RateTypeEnum.Steam;
  }
  if (option.source_kind === UNIT_COOLING_DUTY_SOURCE_KIND) {
    return RateTypeEnum.Electricity;
  }
  return RateTypeEnum.Electricity;
}
 
function selectedObjectIdFromUrl() {
  Iif (typeof window === "undefined") return null;
  const value = new URLSearchParams(window.location.search).get("object");
  if (!value) return null;
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : null;
}
 
function prioritizeSelectedObjectOptions(
  options: OperatingStreamPropertyOption[],
  selectedObjectId: number | null,
) {
  if (selectedObjectId == null) return options;
  return [...options].sort((left, right) => {
    const leftSelected = left.source_object_id === selectedObjectId ? 0 : 1;
    const rightSelected = right.source_object_id === selectedObjectId ? 0 : 1;
    return leftSelected - rightSelected;
  });
}
 
function isSuggestedGroup(value: string): value is SuggestedGroup {
  return (
    value === "utility_consumption" ||
    value === "utility_export" ||
    value === "feedstock" ||
    value === "output"
  );
}
 
function recommendedGroupFor(
  option: OperatingStreamPropertyOption,
): SuggestedGroup {
  Iif (isSuggestedGroup(option.suggested_group)) return option.suggested_group;
  if (option.suggested_group === "energy") return "utility_consumption";
  return "output";
}
 
function propertyLabel(option: OperatingStreamPropertyOption) {
  return option.unit
    ? `${option.display_name} (${option.unit})`
    : option.display_name;
}
 
function isUnexpectedServerError(error: unknown) {
  Iif (!error || typeof error !== "object") return false;
  const status = (error as { status?: unknown }).status;
  Iif (typeof status === "number" && status >= 500) return true;
  const data = (error as { data?: unknown }).data;
  return typeof data === "string" && looksLikeHtmlDocument(data);
}
 
function looksLikeHtmlDocument(value: string) {
  const trimmed = value.trim().toLowerCase();
  return trimmed.startsWith("<!doctype html") || trimmed.startsWith("<html");
}