Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
7.4 kB
1
Indexable
Never
import React, { useEffect } from 'react';
import { withPage, Lift, useAppState } from '@d-lift/core';
import BodySection from '@/Layout/BodySection';
import webService from '@/Services/WebService';
import Questions from './Components/Questions';
import RFIDetails from './Components/RFIDetails';
import SummarizeResponse from './Components/SummarizeResponse';
import SummarizeRFIDetails from './Components/SummarizeRFIDetails';
import { Page } from '@d-lift/uxcomponents';
import './response.scss';
import Moment from 'moment';
import { InteractionType } from '../../../../node_modules/@azure/msal-browser/dist/index';
import { useMsalAuthentication } from '../../../../node_modules/@azure/msal-react/dist/index';

const RFIResponse = () => {
    const [responseData, setResponseData] = useAppState('responseData', false);
    const [rfi, setRfi] = useAppState('rfi');
    const [responseStats, setResponseStats] = useAppState('responseStats', '');
    const [updatedDueDt, setUpdatedDueDt] = useAppState('updatedDueDt', '');
    const [summarizeResponse, setSummarizeResponse] = useAppState('summarizeResponse', false);

    const updateResponseData = (newResponseData) => {
        setResponseData(newResponseData);
    };

    const updateSummarizeResponse = (newState) => {
        setSummarizeResponse(newState);
    };

    const updateRFI = (newState) => {
        setRfi(newState);
    };

    //--------------------This block should be removed once we have email feature enabled in application:START ----------------
    const { result, error } = useMsalAuthentication(InteractionType.Popup, {
        scopes: ['user.read'],
    });
    useEffect(() => {
        // if (error) {
        //     console.log(error);
        //     instance.loginRedirect({
        //         scopes: ['user.read'],
        //     });
        //     return;
        // }
        if (result) {
            const { idToken } = result;
            handleLogin(idToken);
        }
    }, [result, error]);

    const handleLogin = async (idToken) => {
        try {
            Lift.spinner.show();
            let response = await Lift.Application.Security.login(idToken);
        } catch (error) {
            console.log(error);
        } finally {
            Lift.spinner.hide();
        }
    };
    //-----------------------This block should be removed once we have email feature enabled in application:END----------------

    useEffect(() => {
        const urlParams = new URLSearchParams(window.location.search);
        const rfiIdFromURL = urlParams.get('rfi_id');

        if (rfiIdFromURL) {
            loadResponseData(rfiIdFromURL, true);
        } else if (rfi) {
            loadResponseData(rfi.id, false);

            const dueDate = formatDueDate(rfi.dueDT);
            setUpdatedDueDt(dueDate);
        }
    }, [rfi]);

    useEffect(() => {
        if (responseData) {
            const stats = calculateResponseStats(responseData.questions);
            setResponseStats(stats);
        }
    }, [responseData]);

    const loadResponseData = async (rfiId, updateRfiState) => {
        try {
            Lift.spinner.show();

            const response = await webService.getFullDetails({
                requestBody: { rfiId },
            });

            if (response) {
                updateResponseData(response);

                if (updateRfiState) {
                    const urlRfi = {
                        id: response.data.rfiId,
                        title: response.data.title,
                        description: response.data.description,
                        state: response.data.state,
                        dueDT: response.data.dueDT,
                        programs: response.data.programs,
                        category: response.data.category,
                        offering: response.data.offering,
                    };
                    updateRFI(urlRfi);
                }

                // Lift.Application.Notification.success('Response Data loaded successfully');
            }
        } catch (error) {
            console.log(error);
            // Lift.Application.Notification.error('Failed to load Response Data');
        } finally {
            Lift.spinner.hide();
        }
    };

    const formatDueDate = (dueDT) => {
        const dueDate = Moment(dueDT).format('MMM DD, yyyy');

        const parsedDueDate = new Date(dueDT);
        const today = new Date();
        const timeDifference = parsedDueDate - today;

        const daysDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));

        let dueDateText;
        if (daysDifference === 1) {
            dueDateText = `${dueDate} (${daysDifference} day)`;
        } else if (daysDifference > 1) {
            dueDateText = `${dueDate} (${daysDifference} days)`;
        } else if (daysDifference === 0) {
            dueDateText = `${dueDate} (today)`;
        } else if (daysDifference === -1) {
            dueDateText = `${dueDate} (${Math.abs(daysDifference)} day exceeded)`;
        } else if (daysDifference < -1) {
            dueDateText = `${dueDate} (${Math.abs(daysDifference)} days exceeded)`;
        } else {
            dueDateText = `${dueDate} (${daysDifference} days)`;
        }

        return dueDateText;
    };

    const calculateResponseStats = (data) => {
        const totalQuestions = data.length;
        const answeredQuestions = data.filter((q) => q?.answers && q?.answers.length > 0).length;
        const percentageAnswered = Math.round(
            totalQuestions > 0 ? (answeredQuestions / totalQuestions) * 100 : 0,
        );
        return `${answeredQuestions} of ${totalQuestions} (${percentageAnswered}%)`;
    };

    return (
        <Page ref-table-list="OFFERING,STATE,PROGRAM,CATEGORY">
            <BodySection>
                {rfi && !summarizeResponse && (
                    <RFIDetails
                        rfi={rfi}
                        responseStats={responseStats}
                        updatedDueDt={updatedDueDt}
                        summarizeResponse={summarizeResponse}
                        updateSummarizeResponse={updateSummarizeResponse}
                    />
                )}

                {responseData && !summarizeResponse && (
                    <Questions
                        responseData={responseData.questions}
                        updateResponseData={updateResponseData}></Questions>
                )}

                {rfi && summarizeResponse && (
                    <>
                        <SummarizeRFIDetails
                            rfi={rfi}
                            responseStats={responseStats}
                            updatedDueDt={updatedDueDt}
                            summarizeResponse={summarizeResponse}
                            updateSummarizeResponse={updateSummarizeResponse}
                        />
                        {responseData && (
                            <SummarizeResponse
                                summarizeResponse={summarizeResponse}
                                responseData={responseData.questions}
                            />
                        )}
                    </>
                )}
            </BodySection>
        </Page>
    );
};

export default withPage(
    {
        Description: 'Respond to an RFI page',
        ContentManager: true,
        LayoutStyle: 'rfi-dashboard',
    },
    RFIResponse,
);
Leave a Comment