Skip to content
Snippets Groups Projects
SgeConnectView.tsx 6.02 KiB
Newer Older
  • Learn to ignore specific revisions
  • import FormNavigation from 'components/CommonKit/FormNavigation/FormNavigation'
    import FormProgress from 'components/CommonKit/FormProgress/FormProgress'
    
    import Content from 'components/Content/Content'
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
    import CozyBar from 'components/Header/CozyBar'
    
    import Header from 'components/Header/Header'
    
    import useKonnectorAuth from 'components/Hooks/useKonnectorAuth'
    
    import { useClient } from 'cozy-client'
    import { FORM_DOCTYPE } from 'doctypes'
    
    import { FluidType, SgeStep } from 'enums'
    
    import { SgeStore } from 'models'
    
    import React, { useCallback, useEffect, useRef, useState } from 'react'
    
    import { useNavigate } from 'react-router-dom'
    
    import { setShouldRefreshConsent } from 'store/global/global.slice'
    
    import { useAppDispatch, useAppSelector } from 'store/hooks'
    
    import '../connection.scss'
    
    import { createInitialSgeState, useFormData } from '../useForm'
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
    import StepAddress from './StepAddress'
    import StepConsent from './StepConsent'
    import StepIdentityAndPdl from './StepIdentityAndPdl'
    
    export type SGEKeysForm =
      | 'firstName'
      | 'lastName'
      | 'pdl'
      | 'address'
      | 'zipCode'
      | 'city'
      | 'dataConsent'
      | 'pdlConfirm'
    
    /**
     * http://ecolyo.cozy.tools:8080/#/connect/electricity
     */
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
    const SgeConnectView = () => {
    
      const client = useClient()
    
      const navigate = useNavigate()
    
      const dispatch = useAppDispatch()
    
      const { formData } = useFormData()
    
      const [isLoading, setIsLoading] = useState(false)
    
      const [sgeState, setSgeState] = useState<SgeStore>(createInitialSgeState())
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
      const [currentStep, setCurrentStep] = useState<SgeStep>(
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
        SgeStep.IdentityAndPDL
    
      const { fluidStatus } = useAppSelector(state => state.ecolyo.global)
      const currentFluidStatus = fluidStatus[FluidType.ELECTRICITY]
      const account = currentFluidStatus.connection.account
    
    
      const mainContentRef = useRef<HTMLDivElement>(null)
      const focusMainContent = () => {
        setTimeout(() => mainContentRef.current?.focus(), 0)
      }
    
    
      const [connect, update] = useKonnectorAuth(FluidType.ELECTRICITY, {
    
        sgeAuthData: sgeState,
    
      useEffect(
        function applyFormData() {
          if (formData) {
            setSgeState(prevState => ({
              ...prevState,
              ...createInitialSgeState(formData),
            }))
          }
        },
        [formData]
      )
    
    
      useEffect(() => {
        async function launchConnect() {
    
          if (sgeState.shouldLaunchAccount) {
            setSgeState({ ...sgeState, shouldLaunchAccount: false })
    
            dispatch(setShouldRefreshConsent(false))
            if (!account) {
              await connect()
            } else {
              await update()
            }
            navigate('/consumption/electricity')
          }
        }
        launchConnect()
    
      }, [account, connect, sgeState, dispatch, navigate, update])
    
    
      const isNextValid = useCallback(() => {
        switch (currentStep) {
          case SgeStep.IdentityAndPDL:
            return (
    
              sgeState.firstName !== '' &&
              sgeState.lastName !== '' &&
              sgeState.pdl !== null &&
              sgeState.pdl.toString().length === 14
    
            )
          case SgeStep.Address:
            return (
    
              sgeState.address !== '' &&
              sgeState.city !== '' &&
              sgeState.zipCode !== null &&
              sgeState.zipCode.toString().length === 5
    
            )
          case SgeStep.Consent:
    
            return sgeState.dataConsent && sgeState.pdlConfirm
    
          default:
            return false
        }
      }, [
    
        sgeState.address,
        sgeState.city,
        sgeState.dataConsent,
        sgeState.firstName,
        sgeState.lastName,
        sgeState.pdl,
        sgeState.pdlConfirm,
        sgeState.zipCode,
    
        currentStep,
      ])
    
      const handleNext = useCallback(() => {
    
        if (currentStep < SgeStep.Consent) {
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
          setCurrentStep(prev => prev + 1)
    
    
          client.save({
            ...formData,
            _type: FORM_DOCTYPE,
            firstName: sgeState.firstName,
            lastName: sgeState.lastName,
            pdl: sgeState.pdl,
            address: sgeState.address,
            city: sgeState.city,
            zipCode: sgeState.zipCode,
          })
    
        if (currentStep === SgeStep.Consent && !isLoading) {
    
          const updatedState = {
    
            ...sgeState,
            city: sgeState.city.trim(),
    
            shouldLaunchAccount: true,
          }
    
          setSgeState(updatedState)
    
      }, [currentStep, isLoading, client, formData, sgeState])
    
    
      const handlePrev = useCallback(() => {
        if (currentStep !== SgeStep.IdentityAndPDL) {
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
          setCurrentStep(prev => prev - 1)
    
      }, [currentStep])
    
    
      const onChange = useCallback(
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
        (
          key: SGEKeysForm,
          value: string | boolean | number,
          maxLength?: number
        ) => {
    
          if (maxLength && value.toString().length > maxLength) return
    
          const updatedState = {
    
            ...sgeState,
    
            [key]: value,
    
          setSgeState(updatedState)
    
        [sgeState]
    
      )
    
      const renderStep = (step: SgeStep) => {
        switch (step) {
          case SgeStep.Address:
    
            return <StepAddress sgeState={sgeState} onChange={onChange} />
    
          case SgeStep.Consent:
    
            return <StepConsent sgeState={sgeState} onChange={onChange} />
    
          case SgeStep.IdentityAndPDL:
          default:
    
            return <StepIdentityAndPdl sgeState={sgeState} onChange={onChange} />
    
          <CozyBar titleKey="common.title_sge_connect" displayBackArrow={true} />
    
          <Header
    
            desktopTitleKey="common.title_sge_connect"
    
            displayBackArrow={true}
    
            <div ref={mainContentRef} className="connectView" tabIndex={-1}>
    
              <div className="stepContainer">
    
                <FormProgress
                  currentStep={currentStep}
                  totalSteps={Object.values(SgeStep).length / 2}
                />
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
                {renderStep(currentStep)}
              </div>
    
              <FormNavigation
                handlePrevious={handlePrev}
                handleNext={handleNext}
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
                disablePrevButton={currentStep === SgeStep.IdentityAndPDL}
    
                disableNextButton={!isNextValid() || isLoading}
                isLastStep={currentStep === SgeStep.Consent}
    
              />
            </div>
          </Content>
        </>
      )
    }
    
    export default SgeConnectView