All files / src/pages/flowsheet-page/pinch-analysis SegmentTable.tsx

80.9% Statements 89/110
83.67% Branches 41/49
88.23% Functions 30/34
81% Lines 81/100

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 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601                                                                                                                                      62x       140x                   781x     1x                     961x                                                   140x                           781x 421x           140x                         781x 421x                 140x                   781x 421x         140x                           781x 421x         140x                           781x   421x   421x                                                 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 20x 12x   140x 140x 140x       1x   1x 1x   2x 1x   1x   1x 1x 1x     140x                 78x                               140x 140x     140x 140x 140x 140x 140x       5x 5x   49x                                     7x         7x                                                               5x             5x 5x 5x 5x                         5x       1x                         840x                 5x                         398x                                           140x   980x                                     781x     5467x                                                                       140x             140x             7x                 7x                     398x                           700x           35x                                                      
import {
  ColumnDef,
  ExpandedState,
  flexRender,
  getCoreRowModel,
  getExpandedRowModel,
  getFilteredRowModel,
  getSortedRowModel,
  SortingState,
  useReactTable,
} from "@tanstack/react-table";
import { ChevronDown, ChevronRight, PlusIcon, X } from "lucide-react";
import { memo, useMemo, useState } from "react";
import {
  AccessControlledButton as Button,
  AccessControlledInput as Input,
} from "@/ahuora-design-system/ui/accessControlled";
import { Checkbox } from "@/ahuora-design-system/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/ahuora-design-system/ui/dialog";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow,
} from "@/ahuora-design-system/ui/table";
import {
  AbstractionTypeEnum,
  CustomSegment,
  useGraphicsgroupingsCreateCustomGroupCreateMutation,
  usePinchHenNodeDestroyMutation,
  usePinchSegmentCreateNewSegmentCreateMutation,
  usePinchSegmentDestroyMutation,
  usePinchSegmentPartialUpdateMutation,
} from "@/api/apiStore.gen";
import { useFlowsheetAccess } from "@/hooks/flowsheetAccess";
import { useCurrentHenNodes } from "@/hooks/henHooks";
import {
  useCurrentSegments,
  useCurrentStreamDataZones,
} from "@/hooks/PinchHooks";
import { HeaderWithTooltipSortable } from "./TableColumns/HeaderWithTooltipSortable";
 
declare module "@tanstack/react-table" {
  interface TableMeta<TData> {
    updateHTC?: (id: number, htc: number) => void;
    readOnly?: boolean;
  }
}
 
const columns: ColumnDef<CustomSegment>[] = [
  {
    accessorKey: "select-col",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        disabled={Boolean(table.options.meta?.readOnly)}
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
      />
    ),
    cell: ({ row, table }) => (
      <Checkbox
        checked={row.getIsSelected()}
        disabled={Boolean(table.options.meta?.readOnly)}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
      />
    ),
  },
  {
    accessorKey: "name",
    header: "Name",
    cell: ({ row, getValue }) => {
      return (
        <div className="flex items-center">
          {Array.from({ length: row.depth }).map((_, index) => (
            <div key={index} className="w-6"></div>
          ))}
 
          {row.original.type !== "Segment" ? (
            <Button
              variant="ghost"
              className="cursor-pointer p-0"
              onClick={row.getToggleExpandedHandler()}
            >
              {getValue<string>()}
 
              {row.getIsExpanded() && row.original.children?.length !== 0 ? (
                <ChevronDown />
              ) : (
                <ChevronRight />
              )}
            </Button>
          ) : (
            getValue<string>()
          )}
        </div>
      );
    },
  },
  {
    header: ({ column }) => (
      <HeaderWithTooltipSortable
        column={column}
        headerName={
          <>
            T<sub>supply</sub>
          </>
        }
        tooltipContent="Stream supply temperature"
        units={"°C"}
      />
    ),
    inputType: "number",
    accessorKey: "t_supply",
    cell: (cell) => {
      if (cell.getValue<number>() == null) return null;
      return cell.getValue<number>().toFixed(2);
    },
  },
  {
    accessorKey: "t_target",
    header: ({ column }) => (
      <HeaderWithTooltipSortable
        column={column}
        headerName={
          <>
            T<sub>target</sub>
          </>
        }
        tooltipContent="Stream target temperature"
        units={"°C"}
      />
    ),
    inputType: "number",
    cell: (cell) => {
      if (cell.getValue<number>() == null) return null;
      return cell.getValue<number>().toFixed(2);
    },
  },
  // { header: 'P Supply', accessorKey: 'p_supply', cell: (cell) => cell.getValue<number>().toFixed(2) },
  // { header: 'P Target', accessorKey: 'p_target', cell: (cell) => cell.getValue<number>().toFixed(2) },
  // { header: 'H Supply', accessorKey: 'h_supply', cell: (cell) => cell.getValue<number>().toFixed(2) },
  // { header: 'H Target', accessorKey: 'h_target', cell: (cell) => cell.getValue<number>().toFixed(2) },
  {
    header: ({ column }) => (
      <HeaderWithTooltipSortable
        column={column}
        headerName={<>&Delta;H</>}
        tooltipContent="Heat flow"
        units={"kW"}
      />
    ),
    accessorKey: "heat_flow",
    inputType: "number",
    cell: (cell) => {
      if (cell.getValue<number>() == null) return null;
      return cell.getValue<number>().toFixed(2);
    },
  },
  {
    header: ({ column }) => (
      <HeaderWithTooltipSortable
        column={column}
        headerName={
          <>
            &Delta;T<sub>cont</sub>
          </>
        }
        tooltipContent="Stream contribution to minimum approach temperature"
        units={"°C"}
      />
    ),
    accessorKey: "dt_cont",
    inputType: "number",
    cell: (cell) => {
      if (cell.getValue<number>() == null) return null;
      return cell.getValue<number>().toFixed(2);
    },
  },
  {
    header: ({ column }) => (
      <HeaderWithTooltipSortable
        column={column}
        headerName={<>HTC</>}
        tooltipContent="Heat transfer coefficient."
        units={"kW/m²/°C"}
      />
    ),
    accessorKey: "htc",
    inputType: "number",
    // cell: (cell) => {
    // if (cell.getValue<number>() == null) return null;
    // return cell.getValue<number>().toFixed(2);
    // }
    cell: ({ row, getValue, table }) => {
      if (row.original.type !== "Segment") return null;
 
      const val = getValue<number | null>();
 
      return (
        <Input
          defaultValue={val ?? undefined}
          disabled={Boolean(table.options.meta?.readOnly)}
          onBlur={(e) => {
            if (table.options.meta?.readOnly) {
              return;
            }
            const n = Number(e.target.value);
            if (Number.isFinite(n)) {
              // if valid number, patch it.
              table.options.meta?.updateHTC?.(row.original.id, n);
            }
          }}
        />
      );
    },
  },
];
 
function SegmentTable({
  setExcludedSegments,
}: {
  setExcludedSegments: (segments: number[]) => void;
}) {
  const access = useFlowsheetAccess();
  const canMutate = access?.can_edit ?? true;
  const [createSegment] = usePinchSegmentCreateNewSegmentCreateMutation();
  const [updateSegment] = usePinchSegmentPartialUpdateMutation();
  const [deleteSegment] = usePinchSegmentDestroyMutation();
  const [deleteHenNode] = usePinchHenNodeDestroyMutation();
  const [createZone] = useGraphicsgroupingsCreateCustomGroupCreateMutation();
  const { streams } = useCurrentSegments();
  const { data: henNodes, refetch: refetchHenNodes } = useCurrentHenNodes();
  const { zones, isLoading, isError } = useCurrentStreamDataZones();
  const data = useMemo(() => {
    if (!streams) return [];
    return [streams];
  }, [streams]);
  const [expanded, setExpanded] = useState<ExpandedState>(true);
  const [rowSelection, setRowSelection] = useState({});
  const [sorting, setSorting] = useState<SortingState>([]);
 
  const handleRowSelection = (updater) => {
    const newRowSelection =
      typeof updater === "function" ? updater(rowSelection) : updater;
 
    const rowIds = Object.keys(newRowSelection);
    const originalIdsFromRowIds = rowIds
      .map((id) => {
        const row = table.getRowModel().flatRows.find((r) => r.id === id);
        return row.original.id;
      })
      .filter((id) => id !== null && id !== undefined);
 
    setExcludedSegments(originalIdsFromRowIds);
    console.log(originalIdsFromRowIds);
    setRowSelection(newRowSelection);
  };
 
  const table = useReactTable({
    data,
    columns: columns,
    state: {
      expanded,
      rowSelection,
      sorting,
    },
    onExpandedChange: setExpanded,
    getSubRows: (row) => row.children,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
    onRowSelectionChange: handleRowSelection,
    onSortingChange: setSorting,
    getSortedRowModel: getSortedRowModel(),
    // paginateExpandedRows: false,
    meta: {
      updateHTC: (id, htc) =>
        updateSegment({ id: id, patchedSegment: { htc } }),
      readOnly: !canMutate,
    },
  });
 
  function getExcludedRows() {
    const keys = Object.keys(rowSelection);
    return keys.length;
  }
 
  const [newRow, setNewRow] = useState({});
  const [openDialog, setOpenDialog] = useState(false);
  const [newZoneName, setNewZoneName] = useState("");
  const [parentZone, setParentZone] = useState("");
  const [abstractionType, setAbstractionType] = useState("");
 
  const handleInputChange = (key, value) => {
    if (value === "Create new zone") {
      setOpenDialog(true);
      return;
    }
    setNewRow((prevData) => ({
      ...prevData,
      [key]: value,
    }));
  };
 
  async function handleCreate() {
    if (!canMutate) {
      return;
    }
    if (
      newRow.name &&
      newRow.parentZone &&
      newRow.t_supply &&
      newRow.t_target &&
      newRow.heat_flow &&
      newRow.dt_cont &&
      newRow.htc
    ) {
      await createSegment({
        createSegment: {
          ...newRow,
        },
      }).then(() => {
        setNewRow({});
      });
    }
  }
 
  async function handleDelete(id, streamDataEntryId) {
    if (!canMutate) {
      return;
    }
    deleteSegment({
      id: id,
    });
    // delete HENNode
    Iif (!henNodes) return;
    const henNode = henNodes.find(
      (h) => h.stream_data_entry === streamDataEntryId,
    );
    Iif (!henNode) return;
 
    const henNodeId = henNode.id;
    await deleteHenNode({ id: henNodeId }).unwrap();
    await refetchHenNodes?.();
  }
 
  async function handleCreateZone() {
    if (!canMutate) {
      return;
    }
    if (!newZoneName || !parentZone || !abstractionType) {
      alert("Please fill in all fields to create a new zone.");
      return;
    }
    await createZone({
      customGrouping: {
        group: parentZone,
        componentName: newZoneName,
        abstractionType: abstractionType,
      },
    });
    handleInputChange("parentZone", newZoneName);
    setOpenDialog(false);
    setNewZoneName("");
    setParentZone("");
  }
 
  return (
    <ScrollArea className="h-full">
      <Dialog open={openDialog} onOpenChange={setOpenDialog}>
        <DialogContent className="sm:max-w-[425px] flex flex-col gap-6">
          <DialogHeader>
            <DialogTitle>Create New Zone</DialogTitle>
          </DialogHeader>
          <Input
            placeholder="New zone name"
            value={newZoneName}
            onChange={(e) => setNewZoneName(e.target.value)}
          />
          <div className="flex items-center justify-between gap-3">
            <Select
              onValueChange={(value) => setAbstractionType(value)}
              value={abstractionType}
              disabled={!canMutate}
            >
              <SelectTrigger
                className="w-[180px]"
                data-testid="new-zone_set-abstraction-type-dialog"
              >
                <SelectValue placeholder="Abstraction type" />
              </SelectTrigger>
              <SelectContent>
                <SelectGroup>
                  {Object.values(AbstractionTypeEnum).map((type) => (
                    <SelectItem key={type} value={type}>
                      {type}
                    </SelectItem>
                  ))}
                </SelectGroup>
              </SelectContent>
            </Select>
 
            <Select
              onValueChange={(value) => setParentZone(value)}
              value={parentZone}
              disabled={!canMutate}
            >
              <SelectTrigger
                className="w-[180px]"
                data-testid="parent-zone_create-zone-dialog"
              >
                <SelectValue placeholder="Parent zone" />
              </SelectTrigger>
              <SelectContent>
                <SelectGroup>
                  {zones?.map((zone) => (
                    <SelectItem key={zone} value={zone}>
                      {zone}
                    </SelectItem>
                  ))}
                </SelectGroup>
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button onClick={handleCreateZone} aria-label="create-zone">
              Create zone
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <>
        <div className="flex items-center justify-between mb-3">
          <p>Excluding ({getExcludedRows()}) selected rows from analysis</p>
        </div>
        <Table className="border h-full">
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => {
                  return (
                    <TableHead key={header.id} colSpan={header.colSpan}>
                      {header.isPlaceholder ? null : (
                        <div>
                          {flexRender(
                            header.column.columnDef.header,
                            header.getContext(),
                          )}
                        </div>
                      )}
                    </TableHead>
                  );
                })}
                <TableHead></TableHead>
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.map((row) => {
              return (
                <TableRow key={row.id}>
                  {row.getVisibleCells().map((cell) => {
                    return (
                      <TableCell key={cell.id}>
                        {cell.getIsPlaceholder()
                          ? null
                          : flexRender(
                              cell.column.columnDef.cell,
                              cell.getContext(),
                            )}
                      </TableCell>
                    );
                  })}
                  <TableCell>
                    {row.original.custom && (
                      <Button
                        size="icon"
                        variant="ghost"
                        className="h-fit p-0"
                        onClick={() =>
                          handleDelete(
                            row.original.id,
                            row.original.stream_data_entry,
                          )
                        }
                      >
                        <X />
                      </Button>
                    )}
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
          <TableFooter className="sticky bottom-0">
            <TableRow>
              {columns.map((column) => {
                if (column.accessorKey === "select-col") {
                  return (
                    <TableCell key={column.accessorKey}>
                      <div className="w-5"></div>
                    </TableCell>
                  );
                }
                if (column.accessorKey === "name") {
                  return (
                    <TableCell key={column.accessorKey}>
                      <div className="flex gap-2 w-[260px]">
                        <Input
                          placeholder="New stream name"
                          className="p-0"
                          onChange={(e) =>
                            handleInputChange(
                              column.accessorKey,
                              e.target.value,
                            )
                          }
                          value={newRow[column.accessorKey] ?? ""}
                        />
                        <Select
                          onValueChange={(value) =>
                            handleInputChange("parentZone", value)
                          }
                          value={newRow["parentZone"] ?? ""}
                          disabled={!canMutate}
                        >
                          <SelectTrigger className="w-[180px]">
                            <SelectValue placeholder="Parent zone" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectGroup>
                              {zones?.map((zone) => (
                                <SelectItem key={zone} value={zone}>
                                  {zone}
                                </SelectItem>
                              ))}
                              <SelectItem value="Create new zone">
                                Create new zone
                              </SelectItem>
                            </SelectGroup>
                          </SelectContent>
                        </Select>
                      </div>
                    </TableCell>
                  );
                }
                return (
                  <TableCell key={column.accessorKey}>
                    <Input
                      type={column.inputType || "text"}
                      value={newRow[column.accessorKey] ?? ""}
                      onChange={(e) =>
                        handleInputChange(column.accessorKey, e.target.value)
                      }
                      className="p-0"
                      placeholder="New value"
                      aria-label={`New ${column.accessorKey}`}
                    />
                  </TableCell>
                );
              })}
              <TableCell>
                <Button
                  size="icon"
                  onClick={handleCreate}
                  aria-label="create-stream"
                >
                  <PlusIcon />
                </Button>
              </TableCell>
            </TableRow>
          </TableFooter>
        </Table>
      </>
    </ScrollArea>
  );
}
 
export default memo(SegmentTable);