Untitled

mail@pastecode.io avatar
unknown
plain_text
8 days ago
6.3 kB
1
Indexable
Never
explain the below code:


import { AppContext, useAppState, withPage } from '@d-lift/core';
import { Page } from '@d-lift/uxcomponents';
import {
    DataTable,
    Header,
    Button,
    Group,
    Section,
    Para,
    Grid,
    Row,
    Column,
} from '@d-lift/uxcomponents';
import React, { Suspense, useEffect } from 'react';

const SummarizeResponse = ({ summarizeResponse, responseData }) => {
    const [rfiSummarizeResponse, setRfiSummarizeResponse] = useAppState('RFISummarizeResponse', []);
    const [csvData, setCsvData] = useAppState('');

    const generateTableProps = (responseData) => {
        let colDataKeys = ['st', ...responseData.map((q, index) => `q${index + 1}`)].join(',');
        let colDefaultHeaders = ['ST', ...responseData.map((item) => item.question)].join(',');
        return { colDataKeys, colDefaultHeaders };
    };

    let { colDataKeys, colDefaultHeaders } = generateTableProps(responseData);

    const formatTableData = (responseData) => {
        let stateAnswerMaps = {};

        responseData.forEach((item) => {
            if (item.answers && Array.isArray(item.answers)) {
                item.answers.forEach((answer) => {
                    const state = answer.state;
                    if (!stateAnswerMaps[state]) {
                        stateAnswerMaps[state] = {
                            st: state,
                        };

                        responseData.forEach((question, index) => {
                            stateAnswerMaps[state][`q${index + 1}`] = 'N/A';
                        });
                    }

                    const questionIndex = responseData.findIndex((q) => q.id === answer.quesnId);
                    if (questionIndex !== -1) {
                        let questionKey = `q${questionIndex + 1}`;
                        if (!stateAnswerMaps[state][questionKey].includes(answer.answer)) {
                            stateAnswerMaps[state][questionKey] =
                                stateAnswerMaps[state][questionKey] === 'N/A'
                                    ? answer.answer
                                    : `${stateAnswerMaps[state][questionKey]}, ${answer.answer}`;
                        }
                    }
                });
            }
        });

        return Object.values(stateAnswerMaps);
    };

    useEffect(() => {
        if (responseData && Array.isArray(responseData)) {
            const summaryData = formatTableData(responseData);
            setRfiSummarizeResponse(summaryData);
        } else {
            setRfiSummarizeResponse([]);
        }
    }, [responseData]);

    let dataTable = useAppState('RFISummarizeResponse');
    let headers = ['ST', ...responseData.map((item) => item.question)];

    useEffect(() => {
        if (
            dataTable &&
            Array.isArray(dataTable) &&
            dataTable.every((row) => typeof row === 'object' && row !== null)
        ) {
            let csvContent = prepareCSVData(dataTable, headers);
            setCsvData(csvContent);
        } else {
            console.log('Waiting for dataTable to be populated or corrected...');
        }
    }, [dataTable, headers]);

    const prepareCSVData = (dataTable, headers) => {
        if (!Array.isArray(dataTable)) {
            console.error('Invalid data: expected an array', dataTable);
            return '';
        }

        let csvContent = 'data:text/csv;charset=utf-8,';
        if (headers && headers.length > 0) {
            csvContent += headers.join(',') + '\n';
        }

        dataTable[0].forEach((row) => {
            if (typeof row === 'object' && row !== null) {
                let rowContent = Object.values(row).join(',');
                csvContent += rowContent + '\n';
            } else {
                console.error('Unexpected row type:', row);
            }
        });

        return csvContent;
    };
    const downloadCSV = (csvContent) => {
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', 'datatable_export.csv');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    const exportCSV = () => {
        if (!dataTable || !Array.isArray(dataTable) || dataTable[0] === undefined) {
            console.error('Data is not ready for export.');
            return;
        }
        let csvContent = prepareCSVData(dataTable, headers);
        if (csvContent) {
            downloadCSV(csvContent);
        } else {
            console.error('Failed to prepare CSV data');
        }
    };

    return (
        <>
            <Section showIf={summarizeResponse}>
                <Grid>
                    <Row className="mt-5 mb-2">
                        <Column className="col-md-9">
                            <Header
                                className="pt-3 ux-rfi-font-header"
                                size="4"
                                labelKey="responses_header"
                            />
                        </Column>
                        <Column className="col-md-3 d-flex justify-content-end">
                            <Button
                                id="downloadCSV"
                                className="ux-rfi-green-button "
                                labelKey="download_btn"
                                click={exportCSV}
                            />
                        </Column>
                    </Row>
                </Grid>
                <div className="ux-rfi-black-border-round">
                    <DataTable
                        col-data-keys={colDataKeys}
                        col-default-headers={colDefaultHeaders}
                        datacollection="RFISummarizeResponse"
                        className="dt-container"
                        emptymsg-key="Empty_message"
                        keyfield="id"
                        hover="false"
                        striped={false}
                        responsive={true}
                    />
                </div>
            </Section>
        </>
    );
};

export default SummarizeResponse;
Leave a Comment