All files / src/pages/flowsheet-page/flowsheet/Summary ExportExcel.tsx

15.49% Statements 11/71
0% Branches 0/10
13.33% Functions 2/15
16.17% Lines 11/68

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                      12x 12x 12x 12x 12x   12x 12x 12x                                                                                                                                                                                                                                                                                   12x                       22x 22x                      
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/ahuora-design-system/ui/dropdown-menu'
import { Button } from '@/ahuora-design-system/ui/button'
import { Download } from 'lucide-react'
import { GroupWithObject } from '@/hooks/flowsheetObjects'
import { useLazyUnitopsSimulationobjectsCompoundsSummaryRetrieveQuery, useLazyUnitopsSimulationobjectsStreamsSummaryRetrieveQuery, useLazyUnitopsSimulationobjectsUnitopsSummaryRetrieveQuery } from '@/api/apiStore.gen';
import { useLocalStorage } from 'usehooks-ts';
import ExcelJS from "exceljs";
import { saveAs } from "file-saver";
import { useProject } from '@/hooks/project';
 
export default function ExportExcel({ groups }: { groups: GroupWithObject[] | undefined }) {
    const project = useProject()
    const [streamUnitMap] = useLocalStorage('unitMapStreams', {})
    const [unitOpsUnitMap] = useLocalStorage('unitMapUnitops', {})
    const [compoundMode] = useLocalStorage('compoundMode', 'Molar')
    const [measureType] = useLocalStorage('measureType', 'Fraction')
 
    const [triggerStreamFetch] = useLazyUnitopsSimulationobjectsStreamsSummaryRetrieveQuery();
    const [triggerUnitopFetch] = useLazyUnitopsSimulationobjectsUnitopsSummaryRetrieveQuery();
    const [triggerCompoundFetch] = useLazyUnitopsSimulationobjectsCompoundsSummaryRetrieveQuery();
 
    async function fetchByGroups(groupIds: number[]) {
        const [streams, unitops, compounds] = await Promise.all([
            triggerStreamFetch({
                groups: JSON.stringify(groupIds),
                unitMap: JSON.stringify(streamUnitMap)
            }, true).unwrap(),
 
            triggerUnitopFetch({
                groups: JSON.stringify(groupIds),
                unitMap: JSON.stringify(unitOpsUnitMap)
            }, true).unwrap(),
 
            triggerCompoundFetch({
                groups: JSON.stringify(groupIds),
                compoundMode: compoundMode,
                measureType: measureType
            }, true).unwrap()
        ]);
 
        return [streams, unitops, compounds];
    }
 
    function handleExportAll() {
        exportWorkbook(groups?.map(g => g.id) || []);
    }
 
    async function exportWorkbook(groupIds: number[]) {
        const [streams, unitops, compounds] = await fetchByGroups(groupIds);
 
        const selectedGroups = groups?.filter(g => groupIds.includes(g.id));
 
        const workbook = new ExcelJS.Workbook();
        selectedGroups?.forEach((group) => {
            const groupName = group.simulationObjectRead?.componentName || "Flowsheet";
 
            const worksheet = workbook.addWorksheet(groupName);
            const title = worksheet.addRow([
                groupName,
                "Exported:",
                new Date().toLocaleString(),
            ]);
            title.font = { bold: true };
            title.height = 36;
            title.alignment = { vertical: "middle" };
            title.fill = {
                type: "pattern",
                pattern: "solid",
                fgColor: { argb: "e4e4e7" },
            };
 
            worksheet.addRow([]);
 
            addSimulationObjects(streams, streamUnitMap, worksheet, groupName);
 
            worksheet.addRow([]);
            worksheet.addRow([]);
 
            addSimulationObjects(unitops, unitOpsUnitMap, worksheet, groupName);
 
            worksheet.addRow([]);
            worksheet.addRow([]);
 
            addCompounds(compounds, worksheet, groupName);
 
            worksheet.columns.forEach((column) => {
                column.width = 24;
            });
        });
        workbook.xlsx.writeBuffer().then((buffer) => {
            saveAs(
                new Blob([buffer], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                }),
                `${project?.name || "Flowsheet"}.xlsx`,
            );
        });
    }
 
    function addSimulationObjects(simObjs: any, simObjUnitMap: any, worksheet: ExcelJS.Worksheet, groupName: string) {
        for (const [simObjType, simObjContent] of Object.entries(simObjs[groupName])) {
            const simObjData = simObjContent["data"];
            const simObjUnits = simObjContent["units"];
 
            const simObjHeader = worksheet.addRow([simObjType]);
            simObjHeader.font = { bold: true };
            simObjHeader.fill = {
                type: "pattern",
                pattern: "solid",
                fgColor: { argb: "e4e4e7" },
            };
            simObjHeader.alignment = { vertical: "middle"};
 
 
            const columns = Object.keys(simObjData[0]);
            const simObjColumns = worksheet.addRow(columns);
            simObjColumns.font = { bold: true };
 
            const units = columns.map((name) => {
                // if unitmap has it, use that, else use first available unit. 
                // Sometimes column is 'name' which has no units, use empty string then
                return simObjUnitMap[name]?.label || simObjUnits[name]?.[0].label || ""
            });
            worksheet.addRow(units);
 
            for (const simObj of simObjData) {
                const simObjProperties = Object.values(simObj)
                worksheet.addRow(simObjProperties);
            }
            worksheet.addRow([]);
        }
    }
 
    function addCompounds(compounds: any, worksheet: ExcelJS.Worksheet, groupName: string) {
        const compoundsData = compounds[groupName]?.data;
        const compoundsColumns = compounds[groupName]?.columns;
 
        const compoundHeader = worksheet.addRow(["Compounds"]);
        compoundHeader.font = { bold: true };
        compoundHeader.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "e4e4e7" },
        };
        compoundHeader.alignment = { vertical: "middle"};
 
        worksheet.addRow([`${compoundMode} ${measureType}`]);
        
        const columns = worksheet.addRow(compoundsColumns);
        columns.font = { bold: true };
 
        for (const simObj of compoundsData) {
            const values = Object.values(simObj)
            worksheet.addRow(values);
        }
    }
 
    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="outline" size="icon"><Download /></Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-56" align="start">
                <DropdownMenuLabel>Export</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onSelect={() => handleExportAll()}>All layers</DropdownMenuItem>
                <DropdownMenuSeparator />
                {
                    groups?.map((group: GroupWithObject) => {
                        Iif (!group.simulationObjectRead) return null;
                        return (
                            <DropdownMenuItem key={group.id} onSelect={() => exportWorkbook([group.id])}>
                                {group.simulationObjectRead.componentName}
                            </DropdownMenuItem>
                        )
                    })
                }
            </DropdownMenuContent>
        </DropdownMenu>
    )
}