Untitled

 avatar
unknown
plain_text
9 months ago
9.8 kB
2
Indexable
update the below code so that on click of "here" it will be able to pass the rfiurl to copytoclipboard().


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

const RFIRequestForm = ({ rfiRequest, updateRFIRequest, resetRFIRequest }) => {
    const [successMessage, setSuccessMessage] = useAppState('successMessage', false);
    const [rfiUrl, setRfiUrl] = useAppState('rfiUrl', '');

    const generateUniqueKey = () => {
        return Math.floor(Math.random() * 100 + 1);
    };

    const handleAddQuestion = () => {
        let updatedQuestions = [
            ...rfiRequest.questionsList,
            { key: generateUniqueKey(), question: '', description: '' },
        ];
        updateRFIRequest({ ...rfiRequest, questionsList: updatedQuestions });
    };

    const copyToClipboard = (url) => {
        navigator.clipboard
            .writeText(url)
            .then(() => {
                console.log('Text copied to clipboard');
            })
            .catch((err) => {
                console.error('Failed to copy text: ', err);
            });
    };

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

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

            if (createRFIResponse.message.code === ConstantKeys.RESPONSE_CODES.success) {
                resetRFIRequest();
                AppContext.pagedetails.getPageContext().resetValidations();

                const rfiId = createRFIResponse?.data?.id;
                const rfiUrl = `${window.location.origin}/response?rfi_id=${rfiId}`;
                setRfiUrl(rfiUrl);
                setSuccessMessage(true);
            }
        } catch (error) {
            Lift.Application.Notification.error(
                ConstantKeys.NOTIFICATION.MSG.ERR.APPLICATION_ERR_MSG,
            );
        } 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,
                neededBy: Moment(rfiRequest.neededBy).format('yyyy-MM-DD'),
            };
            updateRFIRequest(draftRFIRequest);

            const updatedData = await webService.createRFIRequest({
                requestBody: draftRFIRequest,
            });
            if (updatedData) {
                let neededBy = Moment(updatedData.dueDT).format('MM/DD/yyyy');
                const updatedRfiRequest = {
                    ...updatedData,
                    category: updatedData.category.split(','),
                    programs: updatedData.programs.split(','),
                    neededBy: neededBy,
                    requestedBy: updatedData.state,
                };

                updateRFIRequest(updatedRfiRequest);
                Lift.Application.Notification.success('Draft saved successfully');
            }
        } catch (error) {
            console.log(error);
            Lift.Application.Notification.error(ConstantKeys.NOTIFICATION.MSG.ERR.DRAFT_ERR_MSG);
        } finally {
            Lift.spinner.hide();
        }
    };

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

        if (!questionToDelete.id) {
            // If the question does not have an id, it was added locally and has not been saved to the backend.
            const updatedQuestions = rfiRequest.questionsList.filter((q) => q.key !== key);
            updateRFIRequest({ ...rfiRequest, questionsList: updatedQuestions });
        } else {
            deleteQuestionFromDatabase(questionToDelete.rfiId, questionToDelete.id);
        }
        AppContext.pagedetails.getPageContext().resetValidations();
    };

    const deleteQuestionFromDatabase = async (rfiId, id) => {
        try {
            Lift.spinner.show();
            const deleteResponse = await webService.deleteRFIQuesion({
                requestBody: {
                    rfiId: rfiId,
                    id: id,
                },
            });

            if (deleteResponse.data === id) {
                const updatedQuestions = rfiRequest.questionsList.filter((q) => q.id !== id);
                updateRFIRequest({
                    ...rfiRequest,
                    neededBy: Moment(rfiRequest.neededBy).format('yyyy-MM-DD'),
                    questionsList: updatedQuestions,
                });

                Lift.Application.Notification.success(
                    ConstantKeys.NOTIFICATION.MSG.SUCCESS.QUESTION_DELETE_SUCCESS_MSG,
                );
            }
        } catch (error) {
            console.error('Failed to delete the question from the database', error);
        } finally {
            Lift.spinner.hide();
        }
    };

    return (
        <>
            <PageError
                errorType="success"
                buttonClick={() => copyToClipboard({ rfiUrl })}
                buttonTag={true}
                labelKey="success_message"
                buttonLabelKey="here"
                buttonClass="btn_link"
                closeButtonIcon="fa-fa"
                // showIf={successMessage}
            >
                {/* <span>
                    Application submitted successfully. Please find the rfi-details
                    <a
                        href="#"
                        // onClick={() => copyToClipboard(rfiUrl)}
                    >
                        here
                    </a>
                    .
                </span> */}
            </PageError>
            <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' }}
                maxLength="500"
                required></Textbox>

            <Textarea
                id="noresize"
                maxLength="1000"
                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.key || q.id}
                    index={index}
                    onDeleteQuestion={() => handleDeleteQuestion(q.key || 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"
                            disabled="{true}"
                        />
                    </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;
Editor is loading...
Leave a Comment