Untitled

mail@pastecode.io avatar
unknown
plain_text
15 days ago
8.7 kB
4
Indexable
Never
// after saving the draft application we get the updatedData as  {
        "id": 9351,
        "questionsList": [
            {
                "rfiId": 9351,
                "id": 9851,
                "question": "Question  1",
                "description": "Description 1"
            }
        ],
        "title": "RFI Title",
        "description": "Description",
        "reqDT": "2024-06-05T10:22:09.2292295",
        "state": "WI",
        "programs": "AU",
        "category": "FO",
        "status": "DT",
        "dueDT": "2024-05-27",
        "offering": "EE"
    },

after saving the draft on click of delete button we need to send the "rfiId and id" of the particular question we are clicking delete for INSIDE THE deleteQuestionFromDatabase function, then delete the question deteails from the DB.Update the below code according to the given requirement





import {
    Button,
    Checkbox,
    Column,
    Grid,
    Header,
    Row,
    Textarea,
    Textbox,
    Label,
} from '@d-lift/uxcomponents';
import PropTypes from 'prop-types';
import React from 'react';
import Questionnaire from './Questionnaire';
import webService from '@/Services/WebService';
import ConstantKeys from '@/Constants/ConstantKeys';
import { Lift ,AppContext} from '@d-lift/core';

const RFIRequestForm = ({ rfiRequest, updateRFIRequest , resetRFIRequest}) => {
    const generateUniqueId = () => {
        return Math.floor(Math.random() * 100 + 1);
    };

    const handleAddQuestion = () => {
        console.log(rfiRequest.category, 'categoryList');

        let updatedQuestions = [
            ...rfiRequest.questionsList,
            { id: generateUniqueId(), question: '', description: '' },
        ];
        updateRFIRequest({ ...rfiRequest, questionsList: updatedQuestions });
    };

    const handleSubmit = async () => {
        if (AppContext.pagedetails.getPageContext().validate({ model: 'rfiRequest' }).isError) {
            return;
        }
        try {
            Lift.spinner.show();
            const submitRFIRequest = {
                ...rfiRequest,
                status: ConstantKeys.STATUS_CODES.SUBMITTED,
            };
            updateRFIRequest(submitRFIRequest);

            await webService.createRFIRequest({
                requestBody: submitRFIRequest,
            });

            resetRFIRequest();
            console.log("rfi request after resetting the obj:",rfiRequest);

             // add a code here to Clear the rfiRequest object after successful API hit. set it to the initial value of empty request same as defaultRFIRequest
            Lift.Application.Notification.success('Application submitted Sucessfully');
        } catch (error) {
            Lift.Application.Notification.error('Application could not be submitted');
        } finally {
            Lift.spinner.hide();
        }
    };

    const saveDraft = async () => {
        if (AppContext.pagedetails.getPageContext().validate({ model: 'rfiRequest' }).isError) {
            return;
        }
        try {
            Lift.spinner.show();
            const draftRFIRequest = {
                ...rfiRequest,
                status: ConstantKeys.STATUS_CODES.DRAFT,
            };
            updateRFIRequest(draftRFIRequest);

            const updatedData = await webService.createRFIRequest({
                requestBody: draftRFIRequest,
            });

            if (updatedData) {
                const dueDate = new Date(updatedData.dueDT);
                const formattedDueDt =
                    updatedData.status === 'DT'
                        ? dueDate.toISOString().split('T')[0]
                        : updatedData.neededBy;

                const updatedRfiRequest = {
                    ...updatedData,
                    category: updatedData.category.split(','),
                    programs: updatedData.programs.split(','),
                    neededBy: formattedDueDt,
                };
                updateRFIRequest(updatedRfiRequest);
                Lift.Application.Notification.success('Draft saved Sucessfully');
            }
        } catch (error) {
            console.log(error);
            Lift.Application.Notification.error('Draft could not be saved');
        } finally {
            Lift.spinner.hide();
        }
    };

    const handleDeleteQuestion = (id) => {
        const questionToDelete = rfiRequest.questionsList.find((q) => q.id === id);

        if (questionToDelete) {
            let updatedQuestions = rfiRequest.questionsList.filter((q) => q.id !== id);
            updateRFIRequest({ ...rfiRequest, questionsList: updatedQuestions });
        } else {
            deleteQuestionFromDatabase(id);
        }
    };

    const deleteQuestionFromDatabase = async (id) => {
        try {
            Lift.spinner.show();
            const response = await webService.deleteRFIQuesion(`/questions/${id}`, {
                requestBody: {
                    id: id,
                    rfiId: 1, // hard coding the value as of now
                },
            });

            updateRFIRequest({ ...rfiRequest, questionsList: response.data.updatedQuestions });
            Lift.Application.Notification.success('Question deleted sucessfully');
        } catch (error) {
            console.error('Failed to delete the question from the database', error);
        } finally {
            Lift.spinner.hide();
        }
    };

    return (
        <>
            <Header size="2" labelKey="request_header" className="pt-3 ux-rfi-font-header"></Header>

            <Label className="mb-0 mt-3 mandatory_field" labelKey="title"></Label>

            <Textbox
                name="title"
                model="rfiRequest.title"
                placeholder="Placeholder text"
                className="ux-rfi-remove-padding"
                validationRules="alphaNumericCheck"
                errormessages={{ alphaNumericCheck: 'only_alphabets_allowed' }}
                required></Textbox>

            <Textarea
                id="noresize"
                maxLength="100"
                model="rfiRequest.description"
                placeholderText="Placeholder text"
                validationRules="alphaNumericCheck"
                errormessages={{ alphaNumericCheck: 'only_alphabets_allowed' }}
                rows="5"
                wrap="hard"
                labelKey="request_desc">
                {' '}
            </Textarea>

            {rfiRequest?.questionsList.map((q, index) => (
                <Questionnaire
                    key={q.id}
                    index={index}
                    onDeleteQuestion={() => handleDeleteQuestion(q.id)}
                />
            ))}

            <div className="pt-4">
                <Button
                    id="addQues-btn"
                    size="small"
                    className="ux-rfi-green-button"
                    click={handleAddQuestion}
                    labelKey="addQues_btn"></Button>
            </div>
            <Grid>
                <Row className="mt-5 mb-2">
                    <Column className="col-md-4">
                        <Button
                            id="saveDraft-btn"
                            size="small"
                            className="ux-rfi-green-button"
                            click={saveDraft}
                            labelKey="save_draft_btn"></Button>
                    </Column>
                    <Column className="align-self-center col-md-4 ">
                        <Checkbox
                            id="notification"
                            labelKey="email_notification"
                            model="rfiRequest.email_notification"
                        />
                    </Column>
                    <Column className="col-md-4">
                        <Button
                            id="submit-btn"
                            size="small"
                            className="ux-rfi-green-button float-right"
                            click={handleSubmit}
                            labelKey="submit_btn"></Button>
                    </Column>
                </Row>
            </Grid>
        </>
    );
};

RFIRequestForm.propTypes = {
    rfiRequest: PropTypes.object.isRequired,
    updateRFIRequest: PropTypes.func.isRequired,
    resetRFIRequest: PropTypes.func.isRequired,
};
export default RFIRequestForm;
Leave a Comment