Untitled

 avatar
unknown
plain_text
a year ago
15 kB
6
Indexable
Update the below code so that if the person do not have access to that state then he can't edit the response(disable the edit response button). if the state is not present in the filteredStates list then disable the edit response button for the answers from that state.



import React, { useState, useEffect } from 'react';
import {
    Accordian,
    AccordianElement,
    Label,
    Button,
    Modal,
    Para,
    Selectbox,
    Group,
    Textarea,
    UX,
    FieldError,
} from '@d-lift/uxcomponents';
import PropTypes from 'prop-types';
import '@/Validations/customValidations';
import { useAppState, Lift, AppContext, Util } from '@d-lift/core';
import webService from '@/Services/WebService';
import rfiUtil from '@/Util/RFIUtil';
import ConstantKeys from '@/Constants/ConstantKeys';
import { set } from 'lodash';

const Questions = ({ responseData, updateResponseData }) => {
    const [openModal, setOpenModal] = useAppState('openModal', false);
    const [stateResponse, setStateResponse] = useAppState('stateResponse', {
        state: '',
        answer: '',
    });
    const [currentQuestion, setCurrentQuestion] = useState(null);
    const [editMode, setEditMode] = useState({ questionId: null, answerId: null });

    const [filteredStates, setFilteredStates] = useAppState('filteredStates', []);
    const [existingStatesResp, setExistingStatesResp] = useAppState('existingStatesResp', false);

    const refTableContent = rfiUtil.getRefTableDataByCacheName(
        ConstantKeys.REF_TABLE.CREATE_RFI_REF_TABLES,
    );

    useEffect(() => {
        const stateList = rfiUtil.getAuthorizedStateList();
        if (refTableContent) {
            const filteredStateValues = refTableContent.STATE.filter((state) =>
                stateList.includes(state.CODE),
            );
            setFilteredStates(filteredStateValues);
        }
    }, []);

    const getStateDsc = (stateCode) => {
        return Util.getRefTableDescriptionByCode(ConstantKeys.REF_TABLE_NAMES.STATE, stateCode);
    };

    const showResponseModal = (question) => {
        setCurrentQuestion(question);
        setStateResponse({ state: '', answer: '' });
        setOpenModal(true);
        AppContext.pagedetails.getPageContext().clearValidations();
    };

    const hideResponseModal = () => {
        setOpenModal(false);
        setStateResponse({ state: '', answer: '' });
        setCurrentQuestion(null);
        setExistingStatesResp(false);
    };

    const handleSaveRfiResponse = async () => {
        try {

            if (AppContext.pagedetails.getPageContext().validate({ model: 'stateResponse' }).isError) {
                return;
            }
            const responseRequest = {
                quesnId: currentQuestion.id,
                id: '',
                answer: stateResponse.answer,
                state: stateResponse.state,
            };

            const response = await webService.submitRFIResponse({
                requestBody: responseRequest,
            });

            if (response.message.code === ConstantKeys.RESPONSE_CODES.sucess) {
                const updatedQuestions = responseData.map((question) => {
                    if (question.id === currentQuestion.id) {
                        let answers = question.answers
                            ? [...question.answers, response.data]
                            : [response.data];
                        question = {
                            ...question,
                            answers: answers,
                        };
                    }
                    return question;
                });

                const updatedResponseObject = {
                    ...responseData,
                    questions: updatedQuestions,
                };

                updateResponseData(updatedResponseObject);

                hideResponseModal();

                Lift.Application.Notification.success('Response saved successfully');
            } else {
                Lift.Application.Notification.error('Response could not be submitted');
            }
        } catch (error) {
            Lift.Application.Notification.error('Response could not be submitted');
        }
        //finally {
        //     Lift.spinner.hide();
        // }
    };

    const toggleEdit = (questionId, answerId, prevAns) => {
        if (prevAns) {
            AppContext.model.setValue('stateResponse.answer', prevAns);
        }

        setEditMode((prevState) =>
            prevState.questionId === questionId && prevState.answerId === answerId
                ? { questionId: null, answerId: null }
                : { questionId, answerId },
        );
    };

    const handleUpdateRfiResponse = async (id, quesnId, state) => {
        try {
            Lift.spinner.show();

            const saveRequest = {
                id: id,
                quesnId: quesnId,
                answer: stateResponse.answer,
                state: state,
            };

            const responseObj = await webService.submitRFIResponse({
                requestBody: saveRequest,
            });

            if (responseObj.message.code === ConstantKeys.RESPONSE_CODES.sucess) {
                const updatedQuestions = responseData.map((question) => {
                    if (question.id === quesnId) {
                        return {
                            ...question,
                            answers: question.answers.map((answer) =>
                                answer.id === id
                                    ? { ...answer, answer: stateResponse.answer }
                                    : answer,
                            ),
                        };
                    }
                    return question;
                });

                const updatedResponseObject = {
                    ...responseData,
                    questions: updatedQuestions,
                };

                updateResponseData(updatedResponseObject);
                toggleEdit(null, null);

                Lift.Application.Notification.success('Response updated successfully');
            } else {
                Lift.Application.Notification.error('Response could not be updated');
            }
        } catch (error) {
            Lift.Application.Notification.error('Response could not be updated');
        } finally {
            Lift.spinner.hide();
        }
    };

    const validateStateValue = (e) => {
        const selectedState = e.target.value;
        const existingAnswer = currentQuestion?.answers.find(
            (answer) => answer.state === selectedState,
        );

        if (existingAnswer) {
            setExistingStatesResp(true);
        } else {
            setExistingStatesResp(false);
        }
    };

    return (
        <div className="ux-rfi-green-border mt-4">
            <Label labelKey="Questions"></Label>

            {responseData?.map((question, index) => (
                <Accordian id={`outer-accordian-${index}`} key={question.id}>
                    <AccordianElement headerText={question.question}>
                        <Label>{question?.answers?.length} &nbsp Responses:</Label>

                        {question?.answers?.map((answer, aIndex) => (
                            <Accordian id={`inner-accordian-${index}-${aIndex}`} key={answer.id}>
                                <AccordianElement headerText={getStateDsc(answer.state)}>
                                    <Para
                                        showIf={
                                            !(
                                                editMode.questionId === question.id &&
                                                editMode.answerId === answer.id
                                            )
                                        }>
                                        {answer.answer}
                                    </Para>

                                    <Textarea
                                        id="response"
                                        showIf={
                                            editMode.questionId === question.id &&
                                            editMode.answerId === answer.id
                                        }
                                        maxLength="100"
                                        model="stateResponse.answer"
                                        placeholderText="Placeholder text"
                                        validationRules="alphaNumericCheck"
                                        errormessages={{
                                            alphaNumericCheck: 'only_alphabets_allowed',
                                        }}
                                        rows="5"
                                        wrap="hard"
                                        onChange={(e) =>
                                            setStateResponse({
                                                ...stateResponse,
                                                answer: e.target.value,
                                            })
                                        }></Textarea>
                                    <Button
                                        id={`edit-btn-${index}-${aIndex}`}
                                        size="small"
                                        className="ux-rfi-green-button float-right mt-2 mb-2"
                                        labelKey="edit_response"
                                        showIf={
                                            !(
                                                editMode.questionId === question.id &&
                                                editMode.answerId === answer.id
                                            )
                                        }
                                        click={() =>
                                            toggleEdit(question.id, answer.id, answer.answer)
                                        }></Button>

                                    <Button
                                        showIf={
                                            editMode.questionId === question.id &&
                                            editMode.answerId === answer.id
                                        }
                                        size="small"
                                        className="ux-rfi-white-button-bold float-left mt-2 mb-2"
                                        click={() => toggleEdit(question.id, answer.id)}
                                        labelKey="cancel_btn"></Button>

                                    <Button
                                        showIf={
                                            editMode.questionId === question.id &&
                                            editMode.answerId === answer.id
                                        }
                                        id={`edit-btn-${index}-${aIndex}`}
                                        size="small"
                                        click={() =>
                                            handleUpdateRfiResponse(
                                                answer.id,
                                                answer.quesnId,
                                                answer.state,
                                            )
                                        }
                                        className="ux-rfi-green-button float-right mt-2 mb-2"
                                        labelKey="save_response"></Button>
                                </AccordianElement>
                            </Accordian>
                        ))}

                        <Button
                            id={`respond-btn-${index}`}
                            size="small"
                            className="ux-rfi-green-button float-right mt-2 mb-2"
                            labelKey="respond_question"
                            click={() => showResponseModal(question)}></Button>
                    </AccordianElement>
                </Accordian>
            ))}

            <Modal isOpen={openModal}>
                <FieldError
                    showIf={existingStatesResp}
                    labelKey="OnStateMatchError"
                    className="pb-2 pt-2"></FieldError>

                <Group width="3,4">
                    <Label className="mandatory_field" labelKey="respond_as" />

                    <Selectbox
                        id="respond_as"
                        model="stateResponse.state"
                        defaultOptionLabelKey="select_state"
                        list="filteredStates"
                        optionLabel={ConstantKeys.REF_TABLE_COLS.DESCRIPTION}
                        optionValue={ConstantKeys.REF_TABLE_COLS.CODE}
                        defaultOption="true"
                        change={validateStateValue}
                        required></Selectbox>
                </Group>
                <Label className="mandatory_field" labelKey="response"/>
                <Textarea
                    id="response"
                    maxLength="100"
                    model="stateResponse.answer"
                    placeholderText="Placeholder text"
                    validationRules="alphaNumericCheck"
                    errormessages={{ alphaNumericCheck: 'only_alphabets_allowed' }}
                    rows="5"
                    wrap="hard"
                    required
                    disabled={existingStatesResp}></Textarea>
                <Group>
                    <Button
                        size="small"
                        className="ux-rfi-white-button-bold float-left mt-3"
                        click={hideResponseModal}
                        labelKey="cancel_btn"></Button>
                    <Button
                        size="small"
                        className="ux-rfi-green-button float-right mt-3"
                        click={handleSaveRfiResponse}
                        labelKey="submit_ans_btn"
                        showIf={existingStatesResp}></Button>
                </Group>
            </Modal>
        </div>
    );
};

Questions.propTypes = {
    responseData: PropTypes.array.isRequired,
    updateResponseData: PropTypes.func.isRequired,
};

export default Questions;
Editor is loading...
Leave a Comment