Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
20 kB
2
Indexable
Never
import classes from './LastStep.module.scss';
import dynamic from 'next/dynamic';
import LastStepButton from '../../atoms/LastStepButton/LastStepButton';
import ImageLoader from '../../../../../common/components/atoms/ImageLoader/ImageLoader';
import { useRouter } from 'next/router';
import Donation from '../../../../Payment/components/organisms/Donation/Donation';
import { createPDFReport } from '../../../services/pdfService';
import { useEffect, useState, useRef, createRef } from 'react';
import Modal from '../../../../../common/components/atoms/Modal/Modal';
import EmailPopup from '../../atoms/LastStep/EmailPopup/EmailPopup';
import { getPaymentContent } from '../../../../Payment/services/paymentLangService';
import { getMultilanguageContent } from '../../../../../common/services/content/multilanguageContent';
import { useSelector, useDispatch } from 'react-redux';
import useWindowDimensions from '../../../../../common/services/useWindowDimensions.js';
import classNames from 'classnames/bind';
import {
  getDashboardTabContent,
  getDashboardAssets,
} from '../../../services/dashboardContentService';
import {
  setGridForSliders,
  setPdfDownloadedOrAdvisorClicked,
} from '../../../../../redux/reducers/chartsDashboardSlice';
import { setLocalStorageValues } from '../../../services/dashboardLocalStorageHendler';
import { REACHED_DASHBOARD } from '../../../helpers/localStorageKeyNames';
import moment from 'moment';
import Spinner from '../../../../../common/components/atoms/Spinner/Spinner';
import { useScreenshot } from 'use-react-screenshot';
import {
  savePDFToFBStorage,
  savePDFToFBStorageForMail,
} from '../../../services/pdfService';
import { sendEmailWith } from '../../../services/mailing';
import { uuidv4 } from '../../../../../common/services/guid';
import { Suspense } from 'react';
import { GENERAL_GOAL } from '../../../helpers/localStorageKeyNames';
import { getLocalStorageValue } from '../../../services/dashboardLocalStorageHendler';
import { pdfContentService } from '../../../services/pdfContentService';
import { getCommonSiteElements } from '../../../services/commonSiteElementsService';
import { handleSnackbar } from '../../../../../redux/reducers/commonSlice';

const PDF = dynamic(() => import('../../atoms/GeneratePDF/PDFBranchABC'), {
  suspense: true,
});

const DONATION_FEATURE_ID = '4skfjWgdHqu1ggGYztBJ';
const LAST_STEP_DOCUMENT_ID = 'TOc8C1VlUVZB70Cih9o2';

const FIRESTORE_BASE_URL = process.env.FIRESTORE_BASE_URL;
const LastStep = ({
  dashboardGoalOutput,
  dashboardPortfolioOutput,
  contentsCommon,
  investmentProposalTableData,
  openCashPart,
  showLastStep,
  setShowLastStep,
}) => {
  const { isOptimalSolution, pdfDownloadedOrAdvisorClicked } = useSelector(
    (state) => state.chartsDashboard
  );
  const { width } = useWindowDimensions();
  const router = useRouter();
  const dispatch = useDispatch();
  const [showModal, setShowModal] = useState(false);
  const [paymentPageContent, setPaymentPageContent] = useState('');
  const [pageContent, setPageContent] = useState([]);
  const [iconAssets, setIconAssets] = useState([]);
  const [imageAssets, setImageAssets] = useState([]);
  const { locale } = useRouter();
  const [generatedPDFdate, setGeneratedPDFdate] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const [changingWidth, setChangingWidth] = useState(false);
  const [pdfContent, setPdfContent] = useState('');
  const [isLastStepBlured, setIsLastStepBlured] = useState(false);
  const [siteElements, setSiteElements] = useState([]);
  const [refInfoData, setRefInfoData] = useState({
    emailLinkPage1Top: 0,
    emailLinkPage1Left: 0,
    emailLinkPage1Height: 0,
    emailLinkPage1Width: 0,
    linkPage1Top: 0,
    linkPage1Left: 0,
    linkPage1Height: 0,
    linkPage1Width: 0,
    mainLinkPage1Top: 0,
    mainLinkPage1Left: 0,
    mainLinkPage1Height: 0,
    mainLinkPage1Width: 0,
    feedbackLinkPage2Top: 0,
    feedbackLinkPage2Left: 0,
    feedbackLinkPage2Height: 0,
    feedbackLinkPage2Width: 0,
    feedbackEmailPage2Top: 0,
    feedbackEmailPage2Left: 0,
    feedbackEmailPage2Height: 0,
    feedbackEmailPage2Width: 0,
    userEmailTop: 0,
    userEmailLeft: 0,
    userEmailHeight: 0,
    userEmailWidth: 0,
  });

  useEffect(async () => {
    setPaymentPageContent(await getPaymentContent(DONATION_FEATURE_ID));
    setPageContent(await getDashboardTabContent(false, LAST_STEP_DOCUMENT_ID));
    const dashboardAssets = await getDashboardAssets();
    setIconAssets(dashboardAssets.iconAssets);
    setImageAssets(dashboardAssets.imageAssets);
    setPdfContent(await pdfContentService());
    setSiteElements(await getCommonSiteElements());
  }, []);

  let investmentProcessesID = '';
  let email = '';
  let user = '';
  let pdfContents = getMultilanguageContent(locale, pdfContent);

  if (typeof window !== 'undefined') {
    investmentProcessesID = JSON.parse(
      window.localStorage.getItem('investmentProcessId')
    );
    email = JSON?.parse(
      window?.localStorage?.getItem('investmentPortfolioModalInput')
    )?.email;
    user = JSON?.parse(
      window?.localStorage?.getItem('investmentPortfolioModalInput')
    )?.name;
  }

  useEffect(() => () => dispatch(setGridForSliders(0)), []);

  let content = getMultilanguageContent(locale, pageContent);
  let paymentContents = getMultilanguageContent(locale, paymentPageContent);
  let contentForSignature = content?.signature;

  const [toggleSidebar, setToggleSidebar] = useState(true);

  const handleExitDashboardClick = () => {
    router.push('/leave');
    setLocalStorageValues({ [REACHED_DASHBOARD]: false });
  };

  let cx = classNames.bind(classes);
  const ref = createRef(null);
  // const [image, takeScreenshot] = useScreenshot({
  //   type: 'image/jpeg',
  //   quality: 0.01,
  // });
  // const getImageForBackground = () => takeScreenshot(ref.current);

  let widthOfPage;
  const changeViewport = () => {
    if (changingWidth === true) {
      widthOfPage = '1236px';
    } else if (changingWidth === false) {
      widthOfPage = '100%';
    }
    return widthOfPage;
  };
  const idFromTable = 'my-table';
  const idFromTable2 = 'my-table2';
  const idFromTable3 = 'my-table3';

  const input = window.document.getElementById('divToPrint');

  const getStartingCapital = () => {
    let startingCapital;
    if (dashboardGoalOutput?.barometer?.initial?.units == 'Hundreds') {
      startingCapital = dashboardGoalOutput?.barometer?.initial?.initialCapital;
    } else if (dashboardGoalOutput?.barometer?.initial.units == 'Thousands') {
      startingCapital =
        dashboardGoalOutput?.barometer.initial?.initialCapital * 1000;
    } else if (dashboardGoalOutput?.barometer?.initial?.units == 'Millions') {
      startingCapital =
        dashboardGoalOutput?.barometer?.initial?.initialCapital * 1000000;
    }
    return startingCapital;
  };
  let startingCapital = getStartingCapital();

  let timeT = '';
  let time1 = '';
  let time2 = '';
  let generalGoal = '';

  if (typeof window !== 'undefined') {
    time1 = JSON.parse(window.localStorage.getItem('time1'));
    time2 = JSON.parse(window.localStorage.getItem('time2'));
    timeT = JSON.parse(localStorage.getItem('timeT'));
    generalGoal = getLocalStorageValue(GENERAL_GOAL);
  }

  let time =
    generalGoal === 'B120' ||
    generalGoal === 'B220' ||
    generalGoal === 'B320' ||
    generalGoal === 'B420'
      ? timeT - new Date().getFullYear()
      : generalGoal === 'C110' || generalGoal === 'C120'
      ? time1
      : generalGoal === 'C210' || generalGoal === 'C220'
      ? dashboardGoalOutput?.trajectories?.initial?.trajectories?.better
          ?.length - 1
      : timeT;

  const getInvestmentProductIdArray = () => {
    let investableProducts = [];
    siteElements?.investableProducts?.map((item) => {
      investableProducts?.push(item.id);
    });
    return investableProducts;
  };

  let investmentProductIdArray = getInvestmentProductIdArray();

  const handlePdfDownloadClick = async () => {
    // await getImageForBackground();
    setIsLastStepBlured(true);
    setIsLoading(true);
    setGeneratedPDFdate(moment().format());
    setChangingWidth(true);
    await handleSendPDF(true);
    // await createPDFReport(
    //   true,
    //   input,
    //   width,
    //   openCashPart,
    //   startingCapital,
    //   time,
    //   pdfContents,
    //   idFromTable,
    //   idFromTable2,
    //   idFromTable3,
    //   siteElements,
    //   investmentProductIdArray,
    //   locale,
    //   refInfoData,
    //   email
    // );
    setChangingWidth(false);
    setIsLastStepBlured(false);
    setIsLoading(false);
    dispatch(setPdfDownloadedOrAdvisorClicked(true));
    await savePDFToFBStorage(
      false,
      investmentProcessesID,
      'QIO GBI Report',
      input,
      width,
      openCashPart,
      startingCapital,
      time,
      pdfContents,
      idFromTable,
      idFromTable2,
      idFromTable3,
      siteElements,
      investmentProductIdArray,
      locale,
      refInfoData,
      email
    );
  };

  const handleSendPDF = async (sendReport) => {
    let pdfName;
    let guid = uuidv4();
    pdfName = investmentProcessesID + '/' + guid;
    if (sendReport) {
      await savePDFToFBStorageForMail(
        true,
        investmentProcessesID,
        guid,
        input,
        width,
        openCashPart,
        startingCapital,
        time,
        pdfContents,
        idFromTable,
        idFromTable2,
        idFromTable3,
        siteElements,
        investmentProductIdArray,
        locale,
        refInfoData,
        email
      );
    }
    sendEmailWith(
      content?.messageForEmailAfterDonwload.replaceAll('\\n', '\n'),
      content?.subjectForEmailAfterDonwload,
      email,
      pdfName,
      sendReport,
      contentForSignature
    );
    triggerSuccessfulSentEmail();
  };

  function triggerSuccessfulSentEmail() {
    dispatch(
      handleSnackbar({
        show: true,
        indicator: 'success',
        title: content?.snackbarMessage?.title,
        message: content?.snackbarMessage?.message,
      })
    );
    // setTimeout(() => {
    //   dispatch(
    //     handleSnackbar({
    //       show: false,
    //     })
    //   );
    // }, 5000);
  }

  return (
    <>
      <div
        className={classes.wrapper}
        ref={ref}
        style={{ width: `${changeViewport()}` }}
      >
        {isLoading && isLastStepBlured && (
          <>
            <div
              className={classes.spinerWrapper}
              // style={{
              //   backgroundImage: `url(${image})`,
              // }}
            ></div>
            <div className={classes.spinner}>
              <Spinner spinnerStyle={'blue'} />
              <h1>{content?.generatingPDF}</h1>
            </div>
          </>
        )}
        <div
          className={cx({
            sidebar: true,
            hide: toggleSidebar,
          })}
        >
          <div className={classes.sidebarTitle}>
            <p>{content?.sidebarTitle}</p>
          </div>
          <div className={classes.sidebarParagraph}>
            <p>
              {content?.sidebarParagraph?.firstPart}
              <span>{content?.sidebarParagraph?.linkName}</span>.{' '}
              {content?.sidebarParagraph?.secondPart}
            </p>
          </div>
          <div className={classes.donationForm}>
            <Donation
              contents={paymentContents}
              setToggleSidebar={setToggleSidebar}
            />
          </div>
        </div>

        <div
          className={cx({
            mainSection: true,
            hide: !toggleSidebar,
          })}
        >
          {iconAssets?.downloadButtonBlue != undefined && (
            <div className={classes.buttonDownloadPdf}>
              <LastStepButton
                buttonText={content?.downloadButton}
                imgWhite={iconAssets.downloadButtonWhite}
                imgBlue={iconAssets?.downloadButtonBlue}
                iconWidth={56}
                iconHeight={35}
                handleOnClick={handlePdfDownloadClick}
              />
            </div>
          )}
          {iconAssets?.sendAdvisorButtonBlue != undefined && (
            <div className={classes.buttonSendAdvisor}>
              <LastStepButton
                buttonText={content?.sendAdvisorButton}
                imgWhite={iconAssets?.sendAdvisorButtonWhite}
                imgBlue={iconAssets?.sendAdvisorButtonBlue}
                handleOnClick={() => {
                  setShowModal(true);
                }}
              />
            </div>
          )}
          {iconAssets?.exitDashboardButtonBlue != undefined && (
            <div className={classes.buttonExitDashboard}>
              <LastStepButton
                buttonText={content?.exitDashboardButton}
                imgWhite={iconAssets?.exitDashboardButtonWhite}
                imgBlue={iconAssets?.exitDashboardButtonBlue}
                handleOnClick={handleExitDashboardClick}
                isExitButton={pdfDownloadedOrAdvisorClicked}
                isLastStepBlured={isLastStepBlured}
              />
            </div>
          )}

          <div className={classes.tabTitle}>
            <h1>{content?.title}</h1>
          </div>
          <div className={classes.tabSubtitle}>
            <p>{content?.subtitle}</p>
          </div>

          <div className={classes.brokerageAccountSerialNumber}>
            <p>1.</p>
          </div>
          <div className={classes.brokerageAccountTitle}>
            <p>{content?.brokerageAccountTitle}</p>
          </div>
          <div className={classes.brokerageAccountSubtitle}>
            <p>
              {content?.brokerageAccountSubtitle?.firstPart}
              <a
                href={content?.brokerageAccountSubtitle?.link}
                target="_blank"
                rel="noreferrer noopener"
              >
                {content?.brokerageAccountSubtitle?.linkName}
              </a>
              {content?.brokerageAccountSubtitle?.secondPart}
            </p>
          </div>
          <div className={classes.brokerageAccountImage}>
            <img
              alt={'brockerage account'}
              name={'brockerage acoount'}
              width={218}
              height={211}
              src={imageAssets?.brockerageAccount}
            />
          </div>
          {/* <div className={classes.banksImage}>
            <ImageLoader
              name={'banks'}
              width={431}
              height={52}
              src={imageAssets?.banksImage}
            />
          </div> */}
          <div className={classes.sectionsGap}></div>
          <div className={classes.yourGoalAssetsSerialNumber}>
            <p>2.</p>
          </div>
          <div className={classes.yourGoalAssetsTitle}>
            <p>{content?.yourGoalAssetsTitle}</p>
          </div>
          <div className={classes.yourGoalAssetsSubtitle}>
            <p>{content?.yourGoalAssetsSubtitle}</p>
            <div className={classes.yourGoalAssetsSubtitleSecondParagraph}>
              <p>
                {content?.yourGoalAssetsParagraph?.firstPart}
                <a
                  href={content?.yourGoalAssetsParagraph?.link}
                  target="_blank"
                  rel="noreferrer noopener"
                >
                  {content?.yourGoalAssetsParagraph?.linkName}
                </a>
                .
              </p>
            </div>
          </div>
          <div className={classes.yourGoalAssetsImage}>
            <img
              alt={' your Goal Assets'}
              name={' your Goal Assets'}
              width={240}
              height={195}
              src={imageAssets?.yourGoalAssetsImage}
            />
          </div>

          <div className={classes.sectionsGap2}></div>

          <div className={classes.monitorGoalAndStrategySerialNumber}>
            <p>3.</p>
          </div>
          <div className={classes.monitorGoalAndStrategyTitle}>
            <p>{content?.monitorGoalAndStrategyTitle}</p>
          </div>
          <div className={classes.monitorGoalAndStrategySubtitle}>
            <p>
              {content?.monitorGoalAndStrategySubtitle?.firstPart}
              <a
                href={content?.monitorGoalAndStrategySubtitle?.link}
                target="_blank"
                rel="noreferrer noopener"
              >
                {content?.monitorGoalAndStrategySubtitle?.linkName}
              </a>
              .
            </p>
          </div>
          <div className={classes.monitorGoalAndStrategyImage}>
            <img
              alt={'monitor Goal And Strategy'}
              name={'monitor Goal And Strategy'}
              width={233}
              height={168}
              src={imageAssets?.monitorGoalAndStrategyImage}
            />
          </div>
          <div className={classes.bottomMessage}>
            <p>{content?.bottomMessage}</p>
          </div>
        </div>
        <Modal
          title={content?.sendAdvisorModal?.title}
          show={showModal}
          onClose={() => setShowModal(false)}
          modalStyle={{ height: '550px' }}
        >
          <EmailPopup
            setShowModal={setShowModal}
            bodyText={content?.sendAdvisorModal?.emailBody
              .replaceAll('\\n', '\n')
              .replace('{GOAL}', contentsCommon?.legacyCode?.title)
              .replace('{USER}', user)}
            sendReport={true}
            emailPopupContent={content?.emailPopup}
            input={input}
            contentsCommon={contentsCommon}
            width={width}
            openCashPart={openCashPart}
            startingCapital={startingCapital}
            time={time}
            pdfContents={pdfContents}
            idFromTable={idFromTable}
            idFromTable2={idFromTable2}
            idFromTable3={idFromTable3}
            siteElements={siteElements}
            investmentProductIdArray={investmentProductIdArray}
            locale={locale}
            refInfoData={refInfoData}
            emailUser={email}
            contentForSignature={contentForSignature}
          />
        </Modal>

        {/* If we go with preview in project uncomment this section */}
        {/* <h1>Preview export PDF</h1>
      <div id="exportCanvas">
        <PDFPreview className={classes.buttonGrid} />
      </div> */}

        <div className={classes.donationBackground}>
          <div
            onClick={() => setToggleSidebar(!toggleSidebar)}
            className={cx({
              donationButton: toggleSidebar,
              hide: !toggleSidebar,
            })}
          >
            <div className={classes.upArrowSign}>
              <ImageLoader
                alt={'expand donation'}
                name={'expand donation'}
                width={12}
                height={7}
                src={iconAssets?.upArrowSign}
              />
            </div>
            <p>{content?.donate}</p>
          </div>

          <div
            onClick={() => setToggleSidebar(!toggleSidebar)}
            className={cx({
              donationButtonClose: !toggleSidebar,
              hideSidebar: toggleSidebar,
            })}
          >
            <div className={classes.closeSign}>
              <ImageLoader
                alt={'close'}
                name={'close'}
                width={21}
                height={21}
                src={iconAssets?.closeSign}
              />
            </div>
          </div>
        </div>

        {dashboardPortfolioOutput != null && (
          <div className={classes.pdf} id="divToPrint">
            <Suspense fallback={`Loading...`}>
              <PDF
                dashboardPortfolioOutput={dashboardPortfolioOutput}
                dashboardGoalOutput={dashboardGoalOutput}
                contentsCommon={contentsCommon}
                generatedPDFdate={generatedPDFdate}
                investmentProposalTableData={investmentProposalTableData}
                openCashPart={openCashPart}
                idFromTable={idFromTable}
                idFromTable2={idFromTable2}
                idFromTable3={idFromTable3}
                refInfoData={refInfoData}
                setRefInfoData={setRefInfoData}
                showLastStep={showLastStep}
              />
            </Suspense>
          </div>
        )}
      </div>
    </>
  );
};
export default LastStep;