diff --git a/.eslintrc.js b/.eslintrc.js index 8b0915b65b3a66d3f0b065f30b4a1b667de74946..bfb6fbe13759988ff367c2faea5cc97844fc7c48 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -8,7 +8,7 @@ module.exports = { 'plugin:react-hooks/recommended', ], parserOptions: { - ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features + ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features sourceType: 'module', // Allows for the use of imports ecmaFeatures: { jsx: true, // Allows for the parsing of JSX diff --git a/src/components/Analysis/AnalysisConsumption.tsx b/src/components/Analysis/AnalysisConsumption.tsx index 2a589da8f8f2ba16c067c01a98b870934a6d1fba..7cda6784ce433262cff69aa6ca42bbbd53f7ab4f 100644 --- a/src/components/Analysis/AnalysisConsumption.tsx +++ b/src/components/Analysis/AnalysisConsumption.tsx @@ -55,7 +55,7 @@ const AnalysisConsumption: React.FC<AnalysisConsumptionProps> = ({ const emptyFluidTypes: FluidType[] = [] for (let i = 0; i < performanceIndicators.length; i++) { - if (performanceIndicators[i] && !performanceIndicators[i].value) { + if (!performanceIndicators[i]?.value) { emptyFluidTypes.push(fluidTypes[i]) } } @@ -210,8 +210,7 @@ const AnalysisConsumption: React.FC<AnalysisConsumptionProps> = ({ </div> {fluidTypes.map( (fluid, index) => - performanceIndicators[fluid] && - performanceIndicators[fluid].value && ( + performanceIndicators[fluid]?.value && ( <AnalysisConsumptionRow key={index} fluid={fluid} diff --git a/src/components/Analysis/ElecHalfHourMonthlyAnalysis.tsx b/src/components/Analysis/ElecHalfHourMonthlyAnalysis.tsx index 3103495adc6741030fbe8755bca0c85e119020ea..505762248b036ed823047b6c168b527b8c585b51 100644 --- a/src/components/Analysis/ElecHalfHourMonthlyAnalysis.tsx +++ b/src/components/Analysis/ElecHalfHourMonthlyAnalysis.tsx @@ -98,7 +98,7 @@ const ElecHalfHourMonthlyAnalysis: React.FC<ElecHalfHourMonthlyAnalysisProps> = aggegatedDate.year, aggegatedDate.month ) - if (subscribed && data && data.length) { + if (subscribed && data?.length) { const aggregatedData = emas.aggregateValuesToDataLoad(data[0]) setenedisAnalysisValues(data[0]) setMonthDataloads(aggregatedData) @@ -222,7 +222,7 @@ const ElecHalfHourMonthlyAnalysis: React.FC<ElecHalfHourMonthlyAnalysisProps> = <span className="text-18-normal"> %</span> </div> <div className="text-18-bold"> - {elecPrice && elecPrice.price + {elecPrice?.price ? ( enedisAnalysisValues.minimumLoad * elecPrice.price diff --git a/src/components/Analysis/MonthlyAnalysis.tsx b/src/components/Analysis/MonthlyAnalysis.tsx index 9349cf5284c3193003ea010af02042a8d2ecb846..acb420d491bb946ad5b439677bb7ad51e96de47b 100644 --- a/src/components/Analysis/MonthlyAnalysis.tsx +++ b/src/components/Analysis/MonthlyAnalysis.tsx @@ -77,10 +77,7 @@ const MonthlyAnalysis: React.FC<MonthlyAnalysisProps> = ({ setPerformanceIndicators(fetchedPerformanceIndicators) setLoadAnalysis(false) for (let i = 0; i < fetchedPerformanceIndicators.length; i++) { - if ( - fetchedPerformanceIndicators[i] && - fetchedPerformanceIndicators[i].value - ) { + if (fetchedPerformanceIndicators[i]?.value) { setLoadAnalysis(true) } } diff --git a/src/components/Analysis/TotalAnalysisChart.tsx b/src/components/Analysis/TotalAnalysisChart.tsx index e7997182a4d1dcfa2779e5c51a2346e89b1d9b06..6d14c65d6f6b08b65c7e38ebce8ba2aa183ae21a 100644 --- a/src/components/Analysis/TotalAnalysisChart.tsx +++ b/src/components/Analysis/TotalAnalysisChart.tsx @@ -50,7 +50,7 @@ const TotalAnalysisChart: React.FC<TotalAnalysisChartProps> = ({ undefined, true ) - if (monthTotalData && monthTotalData.actualData) { + if (monthTotalData?.actualData) { setDataLoadValueDetailArray(monthTotalData.actualData[0].valueDetail) setTotalLoadValue(monthTotalData.actualData[0].value) } diff --git a/src/components/Challenge/ChallengeCardDone.tsx b/src/components/Challenge/ChallengeCardDone.tsx index cdb4ec3e6fef4f618214585842bbe490b03d3e98..eef31ac414686bddea72dc3b43a9f33fe9ec7262 100644 --- a/src/components/Challenge/ChallengeCardDone.tsx +++ b/src/components/Challenge/ChallengeCardDone.tsx @@ -30,7 +30,7 @@ const ChallengeCardDone: React.FC<ChallengeCardDoneProps> = ({ const endDate: DateTime = _userChallenge.endingDate const delta = endDate.diff(startDate, 'days').toObject() - if (delta && delta.days !== undefined) { + if (delta?.days !== undefined) { delta.days = Math.round(delta.days + 1) const label = delta.days == 1 diff --git a/src/components/Charts/UncomingBar.tsx b/src/components/Charts/UncomingBar.tsx index d255d9612610beda91c4d08076623b2f75ef1018..328c59b247f4a911668c702d348923818fa0df27 100644 --- a/src/components/Charts/UncomingBar.tsx +++ b/src/components/Charts/UncomingBar.tsx @@ -31,7 +31,7 @@ const UncomingBar = ({ const barClass = animationEnded ? `bar-UNCOMING ` : `bar-UNCOMING bounce-${ - browser && browser.name !== 'edge' ? '1' : '3' + browser?.name !== 'edge' ? '1' : '3' } delay--${index % 13}` const getBandWidth = (): number => { diff --git a/src/components/Connection/ConnectionResult.tsx b/src/components/Connection/ConnectionResult.tsx index e5e94863b03e0a687dbb1d88b052d31dad6967e0..27d0184d1d68fa64fd170721b791fa53dfd5b72d 100644 --- a/src/components/Connection/ConnectionResult.tsx +++ b/src/components/Connection/ConnectionResult.tsx @@ -119,10 +119,7 @@ const ConnectionResult: React.FC<ConnectionResultProps> = ({ }, [deleteAccountsAndTriggers, dispatch]) useEffect(() => { - if ( - fluidStatus.connection.triggerState && - fluidStatus.connection.triggerState.last_success - ) { + if (fluidStatus.connection.triggerState?.last_success) { const result = DateTime.fromISO( fluidStatus.connection.triggerState.last_success ) @@ -131,9 +128,8 @@ const ConnectionResult: React.FC<ConnectionResultProps> = ({ setLastExecutionDate('-') } if ( - fluidStatus.connection.triggerState && - fluidStatus.connection.triggerState.status === 'errored' && - fluidStatus.connection.triggerState.last_error + fluidStatus.connection.triggerState?.status === 'errored' && + fluidStatus.connection.triggerState?.last_error ) { setStatus('errored') setKonnectorError( @@ -218,9 +214,7 @@ const ConnectionResult: React.FC<ConnectionResultProps> = ({ {lastExecutionDate.toLocaleString()} </div> <div> - {fluidStatus && - fluidStatus.connection && - fluidStatus.connection.konnector && + {fluidStatus?.connection?.konnector && t('konnector_form.issue') + ' ' + fluidStatus.connection.konnector.name + diff --git a/src/components/Connection/FormLogin.tsx b/src/components/Connection/FormLogin.tsx index c184fa7155e7936461b9487879ddf58e7829c9d5..f293e906b4333334c8e27b36798a56b6aa988b50 100644 --- a/src/components/Connection/FormLogin.tsx +++ b/src/components/Connection/FormLogin.tsx @@ -152,7 +152,7 @@ const FormLogin: React.FC<FormLoginProps> = ({ } useEffect(() => { - if (account && account.auth) { + if (account?.auth) { const auth = account.auth const authData = auth if (authData.login) { diff --git a/src/components/Connection/FormOAuth.tsx b/src/components/Connection/FormOAuth.tsx index 5a2378c53a5dc61431b575010a408ad0b595ad46..3bb9b0b428df2039eb9557be6c47424951165fa3 100644 --- a/src/components/Connection/FormOAuth.tsx +++ b/src/components/Connection/FormOAuth.tsx @@ -45,7 +45,7 @@ const FormOAuth: React.FC<FormOAuthProps> = ({ const startOAuth = useCallback(async () => { // If first connexion, send the usage event - if (konnector && konnector.slug && fluidStatus.lastDataDate === null) { + if (konnector?.slug && fluidStatus.lastDataDate === null) { await UsageEventService.addEvent(client, { type: UsageEventType.KONNECTOR_ATTEMPT_EVENT, target: konnector.slug, diff --git a/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx b/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx index 565557ecd29baa51c56b71e848fb15fb21e28f05..7d3c7fa407bfe08039e7d81f900d8403374fe5c9 100644 --- a/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx +++ b/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx @@ -79,16 +79,14 @@ const EstimatedConsumptionModal: React.FC<EstimatedConsumptionModalProps> = ({ {t(`FLUID.${FluidType[FluidType.ELECTRICITY]}.LABEL`)} </span> {t('consumption_visualizer.modal.list1', { - elecPrice: - prices[FluidType.ELECTRICITY] && - prices[FluidType.ELECTRICITY].price, - elecPriceStartDate: - prices[FluidType.ELECTRICITY] && - DateTime.fromISO(prices[FluidType.ELECTRICITY].startDate) - .setZone('utc', { - keepLocalTime: true, - }) - .toLocaleString(), + elecPrice: prices[FluidType.ELECTRICITY]?.price, + elecPriceStartDate: DateTime.fromISO( + prices[FluidType.ELECTRICITY]?.startDate + ) + .setZone('utc', { + keepLocalTime: true, + }) + .toLocaleString(), })} </li> <li> @@ -96,15 +94,14 @@ const EstimatedConsumptionModal: React.FC<EstimatedConsumptionModalProps> = ({ {t(`FLUID.${FluidType[FluidType.WATER]}.LABEL`)} </span> {t('consumption_visualizer.modal.list3', { - waterPrice: - prices[FluidType.WATER] && prices[FluidType.WATER].price, - waterPriceStartDate: - prices[FluidType.WATER] && - DateTime.fromISO(prices[FluidType.WATER].startDate) - .setZone('utc', { - keepLocalTime: true, - }) - .toLocaleString(), + waterPrice: prices[FluidType.WATER]?.price, + waterPriceStartDate: DateTime.fromISO( + prices[FluidType.WATER]?.startDate + ) + .setZone('utc', { + keepLocalTime: true, + }) + .toLocaleString(), })} </li> <li> @@ -112,14 +109,14 @@ const EstimatedConsumptionModal: React.FC<EstimatedConsumptionModalProps> = ({ {t(`FLUID.${FluidType[FluidType.GAS]}.LABEL`)} </span> {t('consumption_visualizer.modal.list2', { - gasPrice: prices[FluidType.GAS] && prices[FluidType.GAS].price, - gasPriceStartDate: - prices[FluidType.GAS] && - DateTime.fromISO(prices[FluidType.GAS].startDate) - .setZone('utc', { - keepLocalTime: true, - }) - .toLocaleString(), + gasPrice: prices[FluidType.GAS]?.price, + gasPriceStartDate: DateTime.fromISO( + prices[FluidType.GAS]?.startDate + ) + .setZone('utc', { + keepLocalTime: true, + }) + .toLocaleString(), })} </li> </ul> diff --git a/src/components/Content/Content.tsx b/src/components/Content/Content.tsx index 0df5633eb4973f5c81f24fb70dbecdf68241ab84..f10cb32c1d0690a06d472f05803608757abaa378 100644 --- a/src/components/Content/Content.tsx +++ b/src/components/Content/Content.tsx @@ -39,7 +39,7 @@ const Content: React.FC<ContentProps> = ({ * Handle Desktop scroll */ const handleWindowScroll = useCallback(() => { - app && app.scrollTo(0, 0) + app?.scrollTo(0, 0) window.scrollTo(0, 0) }, [app]) diff --git a/src/components/Duel/DuelView.tsx b/src/components/Duel/DuelView.tsx index 006f902152d63bf2437802dfe55924c3f035c5e4..58f6704fb6be587ffddc8b3d27b8693eb0886dab 100644 --- a/src/components/Duel/DuelView.tsx +++ b/src/components/Duel/DuelView.tsx @@ -58,8 +58,7 @@ const DuelView: React.FC = () => { ></Header> <Content height={headerHeight}> <div> - {currentChallenge && - currentChallenge.state === UserChallengeState.DUEL ? ( + {currentChallenge?.state === UserChallengeState.DUEL ? ( renderDuel(currentChallenge) ) : ( <DuelError /> diff --git a/src/components/Ecogesture/EcogestureModal.tsx b/src/components/Ecogesture/EcogestureModal.tsx index 8d31c646d0f8c35577bc06a00d92010b0dfe7ac2..863ac6fb278e53d105ea6ab50ee9cb5e6e61436a 100644 --- a/src/components/Ecogesture/EcogestureModal.tsx +++ b/src/components/Ecogesture/EcogestureModal.tsx @@ -53,10 +53,7 @@ const EcogestureModal: React.FC<EcogestureModalProps> = ({ } else { setEcogestureIcon(defaultIcon) } - if ( - currentChallenge && - currentChallenge.exploration.ecogesture_id === ecogesture._id - ) { + if (currentChallenge?.exploration.ecogesture_id === ecogesture._id) { setValidExploration(currentChallenge.exploration.id) } } diff --git a/src/components/Ecogesture/SingleEcogesture.tsx b/src/components/Ecogesture/SingleEcogesture.tsx index 9267cccc37994269bccc4368aadfc3a63d02acc2..b5d479c286f8204fbc14084f4363b555dd26a8a5 100644 --- a/src/components/Ecogesture/SingleEcogesture.tsx +++ b/src/components/Ecogesture/SingleEcogesture.tsx @@ -44,8 +44,7 @@ const SingleEcogesture: React.FC<SingleEcogestureProps> = ({ const [isObjective, setIsObjective] = useState<boolean>(false) const [isLoading, setIsLoading] = useState<boolean>(true) const ecogestureID: string = match.params.id - const selectionCompleted = - location && location.state && location.state.selectionCompleted + const selectionCompleted = location?.state?.selectionCompleted const ecogestureService = useMemo(() => new EcogestureService(client), [ client, @@ -141,13 +140,13 @@ const SingleEcogesture: React.FC<SingleEcogestureProps> = ({ return ecogesture ? ( <> <CozyBar - titleKey={ecogesture && ecogesture.shortName} + titleKey={ecogesture?.shortName} isNotKey={true} displayBackArrow={true} /> <Header setHeaderHeight={defineHeaderHeight} - desktopTitleKey={ecogesture && ecogesture.shortName} + desktopTitleKey={ecogesture?.shortName} displayBackArrow={true} isNotKey={true} ></Header> diff --git a/src/components/FluidChart/FluidChartSlide.tsx b/src/components/FluidChart/FluidChartSlide.tsx index 59847d745905852a7684ba00f5ccd80e2152bc7c..1959cbfab0b9db77cb825fe1ed4ccbb674312350 100644 --- a/src/components/FluidChart/FluidChartSlide.tsx +++ b/src/components/FluidChart/FluidChartSlide.tsx @@ -89,7 +89,7 @@ const FluidChartSlide: React.FC<FluidChartSlideProps> = ({ compareTimePeriod, fluidType === FluidType.MULTIFLUID ) - if (subscribed && graphData && graphData.actualData.length > 0) { + if (subscribed && graphData && graphData?.actualData.length > 0) { setChartData(graphData) setIsDataLoaded(true) dispatch(setLoading(false)) diff --git a/src/components/Home/ConsumptionView.tsx b/src/components/Home/ConsumptionView.tsx index 9902d21d2fabe01e8dcc6c2cb11b177bb86e967e..14d4943bfac029b033dc2ca93701ee8ddcddc5d5 100644 --- a/src/components/Home/ConsumptionView.tsx +++ b/src/components/Home/ConsumptionView.tsx @@ -112,8 +112,7 @@ const ConsumptionView: React.FC<ConsumptionViewProps> = ({ const expiredConsents = [] for (const fluid of fluidStatus) { if ( - fluid.connection.triggerState && - fluid.connection.triggerState.last_error && + fluid.connection.triggerState?.last_error && getKonnectorUpdateError(fluid.connection.triggerState.last_error) === 'error_update_oauth' ) { diff --git a/src/components/Home/FluidButton.tsx b/src/components/Home/FluidButton.tsx index 39cae3cf2cd42eab8bf2871af6ed3a0c6b5290ff..906c83e33855786ab65272f8a0a7445520e3779b 100644 --- a/src/components/Home/FluidButton.tsx +++ b/src/components/Home/FluidButton.tsx @@ -74,8 +74,7 @@ const FluidButton: React.FC<FluidButtonProps> = ({ const serviceIsDown = () => { return ( fluidType !== FluidType.MULTIFLUID && - fluidStatus[fluidType] && - fluidStatus[fluidType].status === FluidState.PARTNER_ISSUE + fluidStatus[fluidType]?.status === FluidState.PARTNER_ISSUE ) } @@ -84,9 +83,7 @@ const FluidButton: React.FC<FluidButtonProps> = ({ if ( (fluidType !== FluidType.MULTIFLUID && isConnected() && isErrored()) || (fluidType !== FluidType.MULTIFLUID && isConnected() && isOutdated()) || - (isConnected() && - fluidStatus[fluidType] && - !fluidStatus[fluidType].lastDataDate) + (isConnected() && !fluidStatus[fluidType]?.lastDataDate) ) { setShowError(true) } diff --git a/src/components/Hooks/useExploration.tsx b/src/components/Hooks/useExploration.tsx index 75c99610d640af84c82abdd29725cac31c0e77bc..9d9d4e0fa81f4f8567f68f838c26376927239c8a 100644 --- a/src/components/Hooks/useExploration.tsx +++ b/src/components/Hooks/useExploration.tsx @@ -26,10 +26,9 @@ const useExploration = (): [string, Dispatch<SetStateAction<string>>] => { useEffect(() => { let subscribed = true if ( - currentChallenge && explorationID && - currentChallenge.exploration.id === explorationID && - currentChallenge.exploration.state === UserExplorationState.ONGOING + currentChallenge?.exploration.id === explorationID && + currentChallenge?.exploration.state === UserExplorationState.ONGOING ) { const checkExplo = async () => { const explorationService = new ExplorationService(client) diff --git a/src/components/Konnector/KonnectorViewerCard.tsx b/src/components/Konnector/KonnectorViewerCard.tsx index b23c5f5fd9534baa80596c20522d52bca48f3222..fe71505d23eba7b514977608f8651d3a97dc2104 100644 --- a/src/components/Konnector/KonnectorViewerCard.tsx +++ b/src/components/Konnector/KonnectorViewerCard.tsx @@ -129,7 +129,7 @@ const KonnectorViewerCard: React.FC<KonnectorViewerCardProps> = ({ const refDate: DateTime = DateTime.fromISO('0001-01-01') let _lastDataDate: DateTime | null = DateTime.fromISO('0001-01-01') for (const fluid of _updatedFluidStatus) { - if (fluid.lastDataDate && fluid.lastDataDate > _lastDataDate) { + if (fluid?.lastDataDate > _lastDataDate) { _lastDataDate = fluid.lastDataDate } } @@ -142,9 +142,8 @@ const KonnectorViewerCard: React.FC<KonnectorViewerCardProps> = ({ const refreshChallengeState = useCallback(async () => { if ( - currentChallenge && - currentChallenge.state === UserChallengeState.DUEL && - currentChallenge.duel.state === UserDuelState.ONGOING + currentChallenge?.state === UserChallengeState.DUEL && + currentChallenge?.duel.state === UserDuelState.ONGOING ) { const challengeService = new ChallengeService(client) const { diff --git a/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx b/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx index a331d9ddb2998c86e383a66746d4e493ec27d8d2..c55433bb15a63647316fb69cf14baeed4acc6130 100644 --- a/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx +++ b/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx @@ -23,7 +23,7 @@ const FluidPerformanceIndicator: React.FC<FluidPerformanceIndicatorProps> = ({ const { t } = useI18n() const iconType = getPicto(fluidType) let displayedValue = '----' - if (performanceIndicator && performanceIndicator.value) { + if (performanceIndicator?.value) { displayedValue = formatNumberValues(performanceIndicator.value).toString() } return ( @@ -51,15 +51,13 @@ const FluidPerformanceIndicator: React.FC<FluidPerformanceIndicatorProps> = ({ {/* condition pas de comparaison possible */} <span className={`${ - performanceIndicator && - performanceIndicator.percentageVariation && - performanceIndicator.percentageVariation > 0 + performanceIndicator?.percentageVariation && + performanceIndicator?.percentageVariation > 0 ? 'negative' : 'positive' }`} > - {performanceIndicator && - performanceIndicator.percentageVariation ? ( + {performanceIndicator?.percentageVariation ? ( performanceIndicator.percentageVariation > 0 ? ( `-${formatNumberValues( performanceIndicator.percentageVariation * 100 diff --git a/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx b/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx index 44380016085d123a1729f10fb9755bee2f04ebe9..83e35540ccc0edebfcc3e8d9ce5b5405ce1d8144 100644 --- a/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx +++ b/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx @@ -31,22 +31,18 @@ const PerformanceIndicatorContent: React.FC<PerformanceIndicatorContentProps> = }: PerformanceIndicatorContentProps) => { const { t } = useI18n() let displayedValue: string - if (performanceIndicator && performanceIndicator.value) + if (performanceIndicator?.value) displayedValue = formatNumberValues(performanceIndicator.value).toString() else displayedValue = '-----' let errorInPerf = false - if (performanceIndicator && !performanceIndicator.value) { + if (!performanceIndicator?.value) { errorInPerf = true } let perf: number | null = null let diffInEuro: number | null = null - if ( - performanceIndicator && - performanceIndicator.value && - performanceIndicator.compareValue - ) { + if (performanceIndicator?.value && performanceIndicator.compareValue) { perf = 100 * (performanceIndicator.value / performanceIndicator.compareValue - 1) diffInEuro = performanceIndicator.value - performanceIndicator.compareValue diff --git a/src/components/ProfileType/ProfileTypeFinished.tsx b/src/components/ProfileType/ProfileTypeFinished.tsx index be6a82b0c28f9351c09d2526f2240e8cef9e9ae1..f7c46a2e5b40aee8f5946c5dcb6c7c0ec40e0d8a 100644 --- a/src/components/ProfileType/ProfileTypeFinished.tsx +++ b/src/components/ProfileType/ProfileTypeFinished.tsx @@ -36,7 +36,7 @@ const ProfileTypeFinished: React.FC<ProfileTypeFinishedProps> = ({ (state: AppStore) => state.ecolyo.challenge ) const handleClick = () => { - if (location && location.pathname === '/ecogesture-form') { + if (location?.pathname === '/ecogesture-form') { history.push('/ecogesture-selection') } else { history.goBack() diff --git a/src/components/Splash/SplashRoot.tsx b/src/components/Splash/SplashRoot.tsx index 8a7c4db8835ca3277fbbc3015a42bf906bed7977..61f90670b8f047ce2cb53bad66747b7596d67f76 100644 --- a/src/components/Splash/SplashRoot.tsx +++ b/src/components/Splash/SplashRoot.tsx @@ -194,17 +194,15 @@ const SplashRoot = ({ fadeTimer = 1000, children }: SplashRootProps) => { ) // Set Notification if exploration state is notification if ( - filteredCurrentOngoingChallenge[0] && - filteredCurrentOngoingChallenge[0].exploration.state === - UserExplorationState.NOTIFICATION + filteredCurrentOngoingChallenge[0]?.exploration.state === + UserExplorationState.NOTIFICATION ) { dispatch(toggleChallengeExplorationNotification(true)) } // Set action to notifcation if action is accomplished if ( - filteredCurrentOngoingChallenge[0] && - filteredCurrentOngoingChallenge[0].action.state === - UserActionState.ONGOING + filteredCurrentOngoingChallenge[0]?.action.state === + UserActionState.ONGOING ) { const actionService = new ActionService(client) const updatedUserChallenge: UserChallenge | null = await actionService.isActionDone( @@ -216,9 +214,8 @@ const SplashRoot = ({ fadeTimer = 1000, children }: SplashRootProps) => { } // Set Notification if action state is notification if ( - filteredCurrentOngoingChallenge[0] && - filteredCurrentOngoingChallenge[0].action.state === - UserActionState.NOTIFICATION + filteredCurrentOngoingChallenge[0]?.action.state === + UserActionState.NOTIFICATION ) { dispatch(toggleChallengeActionNotification(true)) } @@ -226,8 +223,8 @@ const SplashRoot = ({ fadeTimer = 1000, children }: SplashRootProps) => { challenge => challenge.state === UserChallengeState.DUEL ) if ( - filteredCurrentDuelChallenge[0] && - filteredCurrentDuelChallenge[0].duel.state === UserDuelState.ONGOING + filteredCurrentDuelChallenge[0]?.duel.state === + UserDuelState.ONGOING ) { const { updatedUserChallenge, @@ -290,7 +287,7 @@ const SplashRoot = ({ fadeTimer = 1000, children }: SplashRootProps) => { * enable the modal */ if ( - today !== (profile && profile.partnersIssueDate.toISO()) && + today !== profile?.partnersIssueDate.toISO() && isConcernedByPartnerIssue ) { dispatch(setPartnersIssue(true)) diff --git a/src/migrations/migration.ts b/src/migrations/migration.ts index fa923665f993f3c094fdea6a95395a7e1fe1f7bd..d3f8b76da7d415214f6cc26360d32b436d03bcca 100644 --- a/src/migrations/migration.ts +++ b/src/migrations/migration.ts @@ -41,7 +41,7 @@ async function getDocs( options?: MigrationQueryOptions ): Promise<any> { let query: QueryDefinition - if (options && options.scope === 'conso') { + if (options?.scope === 'conso') { query = Q(doctype) .where({}) .indexFields(['year', 'month', 'day']) diff --git a/src/services/account.service.ts b/src/services/account.service.ts index 17f756396e9b4817d3ca7e5ca57e460d6a6bcf8d..fb1bc748735ef9ef1ee3e4d9f0f847125e75e1f0 100644 --- a/src/services/account.service.ts +++ b/src/services/account.service.ts @@ -74,9 +74,7 @@ export default class AccountService { let olderAccountId: string | null = null for (const _trigger of triggers) { if ( - _trigger && - _trigger.cozyMetadata && - _trigger.cozyMetadata.createdAt && + _trigger?.cozyMetadata?.createdAt && DateTime.fromISO(_trigger.cozyMetadata.createdAt, { zone: 'utc', }) < olderDate diff --git a/src/services/challenge.service.ts b/src/services/challenge.service.ts index 6fc4b25a30c3b479e0c584e6650f335622a8422c..563a7c6fa40ad5ae09251a291931bf1f38ad970c 100644 --- a/src/services/challenge.service.ts +++ b/src/services/challenge.service.ts @@ -59,10 +59,7 @@ export default class ChallengeService { userChallenges.forEach((challenge, i) => { if (challenge.state != UserChallengeState.LOCKED) isAllLocked = false if (challenge.state === UserChallengeState.DONE) { - if ( - userChallenges[i + 1] && - userChallenges[i + 1].state === UserChallengeState.LOCKED - ) { + if (userChallenges[i + 1]?.state === UserChallengeState.LOCKED) { userChallenges[i + 1].state = UserChallengeState.UNLOCKED } } diff --git a/src/services/consumption.service.ts b/src/services/consumption.service.ts index 107b36b21b472a9de08e267d02466a27b8d771eb..20486c77ca9b51f6523dfe06c2f84cb1c8b12390 100644 --- a/src/services/consumption.service.ts +++ b/src/services/consumption.service.ts @@ -133,7 +133,7 @@ export default class ConsumptionDataManager { compareMaxTimePeriod, isHome ) - return allData && allData.actualData + return allData?.actualData ? Math.max(...allData.actualData.map(d => d.value)) : 0 } else { @@ -374,7 +374,7 @@ export default class ConsumptionDataManager { fluideType, timeStep ) - if (queryResult && queryResult.data.length > 0) { + if (queryResult?.data.length > 0) { return true } return false @@ -403,7 +403,7 @@ export default class ConsumptionDataManager { singleFluidCharts: ISingleFluidChartData[] //,withComparison: boolean = true ): Datachart | null { - if (singleFluidCharts && singleFluidCharts[0].chartData) { + if (singleFluidCharts[0]?.chartData) { const converterService = new ConverterService() const resultChartData: Datachart = { actualData: [], diff --git a/src/services/consumptionFormatter.service.ts b/src/services/consumptionFormatter.service.ts index 1ca49c7e29637e2c516d7a80aad990348fb6a63d..33f4e5d99ca25b03e5b1adee2dd6604219b28aad 100644 --- a/src/services/consumptionFormatter.service.ts +++ b/src/services/consumptionFormatter.service.ts @@ -97,8 +97,8 @@ export default class ConsumptionFormatterService { if ( fluidStatus.firstDataDate && fluidStatus.lastDataDate && - data.date >= fluidStatus.firstDataDate && - data.date <= fluidStatus.lastDataDate + data.date >= fluidStatus?.firstDataDate && + data.date <= fluidStatus?.lastDataDate ) { return { ...data, diff --git a/src/services/duel.service.ts b/src/services/duel.service.ts index 82bf4af528a04073afd4d2511898bd716a9cc0eb..c52daf9ef4337310bc9ed4903978b97417460835 100644 --- a/src/services/duel.service.ts +++ b/src/services/duel.service.ts @@ -94,7 +94,7 @@ export default class DuelService { undefined, true ) - if (dataLoad && dataLoad.actualData) { + if (dataLoad?.actualData) { dataLoad.actualData.forEach((d: Dataload) => { if ( d.value === -1 || diff --git a/src/services/fluid.service.ts b/src/services/fluid.service.ts index 5569acc917698f01b0492261d7c48613f0a81f3c..eb0b3b08f7e31d4149e11567abfc5c88a9602db9 100644 --- a/src/services/fluid.service.ts +++ b/src/services/fluid.service.ts @@ -27,7 +27,7 @@ export default class FluidService { case 'done': return FluidState.DONE case 'errored': - if (state.last_error && state.last_error === 'LOGIN_FAILED') + if (state?.last_error === 'LOGIN_FAILED') return FluidState.ERROR_LOGIN_FAILED else return FluidState.ERROR default: @@ -158,8 +158,7 @@ export default class FluidService { { fluidType: FluidType.ELECTRICITY, status: - partnersInfo && - partnersInfo.notification_activated && + partnersInfo?.notification_activated && this.isFluidInPartnerIssue( FluidType.ELECTRICITY, this.parseFluidStatus(elecKonnector, elecStatus), @@ -182,8 +181,7 @@ export default class FluidService { { fluidType: FluidType.WATER, status: - partnersInfo && - partnersInfo.notification_activated && + partnersInfo?.notification_activated && this.isFluidInPartnerIssue( FluidType.WATER, this.parseFluidStatus(waterKonnector, waterStatus), @@ -206,8 +204,7 @@ export default class FluidService { { fluidType: FluidType.GAS, status: - partnersInfo && - partnersInfo.notification_activated && + partnersInfo?.notification_activated && this.isFluidInPartnerIssue( FluidType.GAS, this.parseFluidStatus(gasKonnector, gasStatus), diff --git a/src/services/initialization.service.ts b/src/services/initialization.service.ts index 78e02c12a492be297e3fda21548443b9f985ec40..4a02240d4e29fcdd7451407a40fa7392d01002b8 100644 --- a/src/services/initialization.service.ts +++ b/src/services/initialization.service.ts @@ -234,10 +234,7 @@ export default class InitializationService { undefined, true ) - if ( - !loadedEcogestures || - (loadedEcogestures && loadedEcogestures.length === 0) - ) { + if (!loadedEcogestures || loadedEcogestures?.length === 0) { // Populate the doctype with data try { for (const ecogesture of ecogestureData) { @@ -245,10 +242,7 @@ export default class InitializationService { } // Check of created document based on count const checkCount = await ecogestureService.getAllEcogestures() - if ( - !checkCount || - (checkCount && checkCount.length !== ecogestureData.length) - ) { + if (!checkCount || checkCount?.length !== ecogestureData.length) { this._setinitStepError(InitStepsErrors.ECOGESTURE_ERROR) throw new Error( 'initEcogesture: Created ecogesture type entities does not match' @@ -284,10 +278,7 @@ export default class InitializationService { } // Check of created document based on count const checkCount = await ecogestureService.getAllEcogestures() - if ( - !checkCount || - (checkCount && checkCount.length !== ecogestureData.length) - ) { + if (!checkCount || checkCount?.length !== ecogestureData.length) { this._setinitStepError(InitStepsErrors.ECOGESTURE_ERROR) throw new Error( 'initEcogesture: Created ecogesture type entities does not match' @@ -311,7 +302,7 @@ export default class InitializationService { const fpService = new FluidPricesService(this._client) // Populate data if none ecogesture exists const loadedPrices = await fpService.getAllPrices() - if (loadedPrices && loadedPrices.length) { + if (loadedPrices?.length) { log.info('[Initialization] FluidPrices db already created') return true } else { @@ -354,10 +345,7 @@ export default class InitializationService { const challengeService = new ChallengeService(this._client) // Populate data if none challengeEntity exists const loadedChallengeEntity = await challengeService.getAllChallengeEntities() - if ( - !loadedChallengeEntity || - (loadedChallengeEntity && loadedChallengeEntity.length === 0) - ) { + if (!loadedChallengeEntity || loadedChallengeEntity?.length === 0) { // Populate the doctype with data try { for (const challengeEntity of challengeEntityData) { @@ -365,10 +353,7 @@ export default class InitializationService { } // Check of created document const checkCount = await challengeService.getAllChallengeEntities() - if ( - !checkCount || - (checkCount && checkCount.length !== challengeEntityData.length) - ) { + if (!checkCount || checkCount?.length !== challengeEntityData.length) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( 'initChallengeEntity: Created challenge entities does not match' @@ -394,10 +379,7 @@ export default class InitializationService { } // Check of created document const checkCount = await challengeService.getAllChallengeEntities() - if ( - !checkCount || - (checkCount && checkCount.length !== challengeEntityData.length) - ) { + if (!checkCount || checkCount?.length !== challengeEntityData.length) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( 'initChallengeEntity: Created challenge entities does not match' @@ -422,7 +404,7 @@ export default class InitializationService { const duelService = new DuelService(this._client) // Populate data if none DuelEntity exists const loadedDuelTypes = await duelService.getAllDuelEntities() - if (!loadedDuelTypes || (loadedDuelTypes && loadedDuelTypes.length === 0)) { + if (!loadedDuelTypes || loadedDuelTypes?.length === 0) { // Populate the doctype with data try { for (const duelEntity of duelEntityData) { @@ -430,10 +412,7 @@ export default class InitializationService { } // Check of created document const checkCount = await duelService.getAllDuelEntities() - if ( - !checkCount || - (checkCount && checkCount.length !== duelEntityData.length) - ) { + if (!checkCount || checkCount?.length !== duelEntityData.length) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( 'initDuelEntity: Created duel entities does not match' @@ -459,10 +438,7 @@ export default class InitializationService { } // Check of created document const checkCount = await duelService.getAllDuelEntities() - if ( - !checkCount || - (checkCount && checkCount.length !== duelEntityData.length) - ) { + if (!checkCount || checkCount?.length !== duelEntityData.length) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( 'initDuelEntity: Created duel entities does not match' @@ -487,10 +463,7 @@ export default class InitializationService { const quizService = new QuizService(this._client) // Populate data if none quizEntity exists const loadedQuizEntity = await quizService.getAllQuizEntities() - if ( - !loadedQuizEntity || - (loadedQuizEntity && loadedQuizEntity.length === 0) - ) { + if (!loadedQuizEntity || loadedQuizEntity?.length === 0) { // Populate the doctype with data try { for (const quizEntity of quizEntityData) { @@ -498,10 +471,7 @@ export default class InitializationService { } // Check of created document const checkCount = await quizService.getAllQuizEntities() - if ( - !checkCount || - (checkCount && checkCount.length !== quizEntityData.length) - ) { + if (!checkCount || checkCount?.length !== quizEntityData.length) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( 'initQuizEntity: Created quiz entities does not match' @@ -528,10 +498,7 @@ export default class InitializationService { } // Check of created document const checkCount = await quizService.getAllQuizEntities() - if ( - !checkCount || - (checkCount && checkCount.length !== quizEntityData.length) - ) { + if (!checkCount || checkCount?.length !== quizEntityData.length) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( 'initQuizEntity: Created quiz entities does not match' @@ -556,10 +523,7 @@ export default class InitializationService { const explorationService = new ExplorationService(this._client) // Populate data if none explorationEntity exists const loadedExplorationEntity = await explorationService.getAllExplorationEntities() - if ( - !loadedExplorationEntity || - (loadedExplorationEntity && loadedExplorationEntity.length === 0) - ) { + if (!loadedExplorationEntity || loadedExplorationEntity?.length === 0) { // Populate the doctype with data try { for (const explorationEntity of explorationEntityData) { @@ -569,7 +533,7 @@ export default class InitializationService { const checkCount = await explorationService.getAllExplorationEntities() if ( !checkCount || - (checkCount && checkCount.length !== explorationEntityData.length) + checkCount?.length !== explorationEntityData.length ) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( @@ -598,7 +562,7 @@ export default class InitializationService { const checkCount = await explorationService.getAllExplorationEntities() if ( !checkCount || - (checkCount && checkCount.length !== explorationEntityData.length) + checkCount?.length !== explorationEntityData.length ) { this._setinitStepError(InitStepsErrors.CHALLENGES_ERROR) throw new Error( diff --git a/src/services/performanceIndicator.service.ts b/src/services/performanceIndicator.service.ts index 63ce8945685152aa9a9137fa2252b3819212fb1e..2c0697a640536ad04601e80ba5cece02b65a4926 100644 --- a/src/services/performanceIndicator.service.ts +++ b/src/services/performanceIndicator.service.ts @@ -45,7 +45,7 @@ export default class PerformanceIndicatorService { } } else { const i = performanceIndicators.length - 1 - if (performanceIndicators[i] && !performanceIndicators[i].value) { + if (!performanceIndicators[i]?.value) { currentValue = 0 } else { for (const key in performanceIndicators) { @@ -60,7 +60,7 @@ export default class PerformanceIndicatorService { : 0 } } - if (performanceIndicators[i] && !performanceIndicators[i].compareValue) { + if (!performanceIndicators[i]?.compareValue) { compareValue = 0 } else { for (const key in performanceIndicators) { diff --git a/src/services/queryRunner.service.ts b/src/services/queryRunner.service.ts index 1fae7902ebd897dd3a8f10ddc5d88faa75e9c8b2..4d4f5a86d807c5a706a1105cde9af503f48d9da8 100644 --- a/src/services/queryRunner.service.ts +++ b/src/services/queryRunner.service.ts @@ -346,7 +346,7 @@ export default class QueryRunner { ) const result = await this.fetchData(query) - if (result && result.data) { + if (result?.data) { const filteredResult = this.filterDataList(result, timePeriod) const mappedResult: Dataload[] = this.mapDataList(filteredResult) return mappedResult @@ -402,7 +402,7 @@ export default class QueryRunner { result && result.data[0] ? result.data[0].load : 0 ) } - if (result && result.data) { + if (result?.data) { const filteredResult = this.filterDataList(result, maxTimePeriod) const mappedResult = this.mapDataList(filteredResult) if (withDate) { @@ -419,12 +419,9 @@ export default class QueryRunner { const query: QueryDefinition = this.buildFirstDateQuery(fluidType, 1) const result = await this.fetchData(query) if ( - result && - result.data && - result.data[0] && - result.data[0].year && - result.data[0].month && - result.data[0].day + result?.data[0]?.year && + result?.data[0]?.month && + result?.data[0]?.day ) { return DateTime.local( result.data[0].year, @@ -443,12 +440,9 @@ export default class QueryRunner { const query: QueryDefinition = this.buildLastDateQuery(fluidType, 1) const result = await this.fetchData(query) if ( - result && - result.data && - result.data[0] && - result.data[0].year && - result.data[0].month && - result.data[0].day + result?.data[0]?.year && + result?.data[0]?.month && + result?.data[0]?.day ) { return DateTime.local( result.data[0].year, diff --git a/src/services/quiz.service.ts b/src/services/quiz.service.ts index 06f8bec93de2ae73446ab89b0e208580c26436c2..0bd3a0afd8283dd04b5845ab85165615a6e06a5a 100644 --- a/src/services/quiz.service.ts +++ b/src/services/quiz.service.ts @@ -429,7 +429,7 @@ export default class QuizService { timeStep, fluidType ) - if (graphData && graphData.actualData) { + if (graphData?.actualData) { max = Math.max(...graphData.actualData.map(d => d.value)) if (max == -1) { @@ -462,12 +462,7 @@ export default class QuizService { if (graphData && graphData.actualData) { max = Math.max(...graphData.actualData.map(d => d.value)) } - } while ( - max == -1 && - graphData && - graphData.actualData && - !limit.reached - ) + } while (max == -1 && graphData?.actualData && !limit.reached) } if (limit.reached) { const newInterval: TimePeriod = { @@ -488,7 +483,7 @@ export default class QuizService { fluidType ) } - if (graphData && graphData.actualData) { + if (graphData?.actualData) { max = Math.max(...graphData.actualData.map(d => d.value)) graphData.actualData.forEach(d => { if (d.value === max) dateMax = d.date diff --git a/src/services/terms.service.ts b/src/services/terms.service.ts index 2fea47dfd79bf0bdbd9aca89a502a72f0256dacf..6dbc2e55a0c3ed6bac12fb714692e965dce2bf8f 100644 --- a/src/services/terms.service.ts +++ b/src/services/terms.service.ts @@ -37,7 +37,7 @@ export default class TermsService { const { data: [terms], }: QueryResult<Term[]> = await this._client.query(query) - if (terms && terms.accepted) return true + if (terms?.accepted) return true else return false } /** diff --git a/src/targets/services/aggregatorUsageEvents.ts b/src/targets/services/aggregatorUsageEvents.ts index 02e6098c02086f518559052850b98c4df1fbaee8..d9669d2a465dfafa79f60235141a5bfa7208c33b 100644 --- a/src/targets/services/aggregatorUsageEvents.ts +++ b/src/targets/services/aggregatorUsageEvents.ts @@ -388,7 +388,7 @@ const buildProfileWithFuildType = async ( const profile = await new ProfileService(client).getProfile() // If profile is not filled, return empty string - if (profile && !profile.isProfileTypeCompleted) return formatedProfile + if (!profile?.isProfileTypeCompleted) return formatedProfile const date = DateTime.local().setZone('utc', { keepLocalTime: true, }) @@ -396,43 +396,23 @@ const buildProfileWithFuildType = async ( date ) if (fluidType === FluidType.ELECTRICITY) { - if ( - profile && - profileType && - profileType.warmingFluid === WarmingType.ELECTRICITY - ) { + if (profile && profileType?.warmingFluid === WarmingType.ELECTRICITY) { formatedProfile = 'chauffage élec' } - if ( - profile && - profileType && - profileType.warmingFluid === WarmingType.WOOD - ) { + if (profile && profileType?.warmingFluid === WarmingType.WOOD) { formatedProfile = 'chauffage bois' } - if ( - profile && - profileType && - profileType.warmingFluid === WarmingType.FUEL - ) { + if (profile && profileType?.warmingFluid === WarmingType.FUEL) { formatedProfile = 'chauffage fuel' } - if ( - profile && - profileType && - profileType.hotWaterFluid === FluidType.ELECTRICITY - ) { + if (profile && profileType?.hotWaterFluid === FluidType.ELECTRICITY) { if (formatedProfile.length === 0) { formatedProfile = 'ECS' } else { formatedProfile += ':ECS' } } - if ( - profile && - profileType && - profileType.cookingFluid === FluidType.ELECTRICITY - ) { + if (profile && profileType?.cookingFluid === FluidType.ELECTRICITY) { if (formatedProfile.length === 0) { formatedProfile = 'cuisine élec' } else { @@ -445,11 +425,7 @@ const buildProfileWithFuildType = async ( return formatedProfile } } else if (fluidType === FluidType.GAS) { - if ( - profile && - profileType && - profileType.warmingFluid === WarmingType.GAS - ) { + if (profile && profileType?.warmingFluid === WarmingType.GAS) { formatedProfile = 'chauffage gaz' } if (profile && profileType && profileType.hotWaterFluid === FluidType.GAS) { @@ -671,7 +647,7 @@ const sendProfileCount = async (client: Client) => { const sendEmailSubscription = async (client: Client) => { log('info', `sendEmailSubscription`) const profile = await new ProfileService(client).getProfile() - if (profile && profile.sendAnalysisNotification) { + if (profile?.sendAnalysisNotification) { const cameBackFromEmail: Indicator = { createdBy: 'ecolyo', measureName: DaccEvent.SUMMARY_SUBSCRIPTION_MONTHLY, @@ -717,7 +693,7 @@ const sendHalfHourConsumption = async (client: Client) => { }) .startOf('day') .toISODate(), - value: data && data.length > 0 ? 1 : 0, + value: data?.length > 0 ? 1 : 0, } await sendIndicator(halfHourConsumption, client) } @@ -1128,7 +1104,7 @@ const aggregateEvents = async ( : null let starNumbers = 0 - if (currentChallenge && currentChallenge.progress) { + if (currentChallenge?.progress) { starNumbers = currentChallenge.progress.actionProgress + currentChallenge.progress.explorationProgress + diff --git a/src/targets/services/enedisHalfHourMonthlyAnalysis.ts b/src/targets/services/enedisHalfHourMonthlyAnalysis.ts index e7f269b51af3d40f51cf2d904da580f68289da5d..e512b63d28d6773174bd8c09b7db5d2b25f5899e 100644 --- a/src/targets/services/enedisHalfHourMonthlyAnalysis.ts +++ b/src/targets/services/enedisHalfHourMonthlyAnalysis.ts @@ -90,7 +90,7 @@ const getMonthMaxPower = async ( log('info', `Fetching max power for month ${month} of year ${year}`) const data = await emas.getMaxPowerByDate(year, month) const maxPowerArray: number[] = [] - if (data && data.length) { + if (data?.length) { for (const day of data) { maxPowerArray.push(day.load) } @@ -230,9 +230,8 @@ const syncEnedisMonthlyAnalysisDataDoctype = async ({ ENEDIS_MONTHLY_ANALYSIS_DATA_DOCTYPE )) as EnedisMonthlyAnalysisData[] if ( - firstEnedisMonthlyAnalysis && - firstEnedisMonthlyAnalysis[0].month === firstMinuteData[0].month && - firstEnedisMonthlyAnalysis[0].year === firstMinuteData[0].year + firstEnedisMonthlyAnalysis[0]?.month === firstMinuteData[0].month && + firstEnedisMonthlyAnalysis[0]?.year === firstMinuteData[0].year ) { log('info', 'Every Enedis Anlysis already synchronized') return diff --git a/src/targets/services/fluidsPrices.ts b/src/targets/services/fluidsPrices.ts index a57025562299f7b6c79f78f858c3a68803ffa06b..f8ba71ff41315bb690c8f18d97ab91454dd64509 100644 --- a/src/targets/services/fluidsPrices.ts +++ b/src/targets/services/fluidsPrices.ts @@ -167,7 +167,7 @@ const aggregatePrices = async ( // Get doc to update const docToUpdate = await qr.fetchFluidRawDoctype(tp, ts, fluidType) - if (docToUpdate && data && docToUpdate.data && data.data) { + if (docToUpdate?.data && data?.data) { docToUpdate.data[0].price = data.data.map(price).reduce(sum) } // Save updated docs @@ -306,8 +306,7 @@ const applyPrices = async (client: Client, fluidType: FluidType) => { ) // If lastItem has a price, skip this day (in order to save perf) - const lastItem = - data && data.data && data.data[data.data.length - 1] + const lastItem = data?.data && data.data[data.data.length - 1] if (lastItem && priceData) { //if a price has been updated in backoffice re-calculates all price from the firstEditedPriceDate data && diff --git a/src/targets/services/monthlyReportNotification.ts b/src/targets/services/monthlyReportNotification.ts index 6ba377a2a426f2111e005ba7fdde5c193620e461..c58e755189f614f8d7b7004b8b3a612e865deb5a 100644 --- a/src/targets/services/monthlyReportNotification.ts +++ b/src/targets/services/monthlyReportNotification.ts @@ -229,7 +229,7 @@ const monthlyReportNotification = async ({ let unsubscribeUrl userProfil = await upm.getProfile() let token = undefined - if (userProfil && userProfil.mailToken) { + if (userProfil?.mailToken) { token = userProfil.mailToken } diff --git a/src/utils/date.ts b/src/utils/date.ts index 5b558ac8b8e4144e00a64165ad33e981059c4bd4..7ee3c6ad01dc17cb8667f1d8b07039650342d707 100644 --- a/src/utils/date.ts +++ b/src/utils/date.ts @@ -90,17 +90,9 @@ export const isLastPeriodReached = ( * the possible calculation of data based on configured fluidTypes */ export const getLagDays = (fluidTypes: FluidType[]): number => { - if ( - fluidTypes && - fluidTypes.length > 0 && - fluidTypes.includes(FluidType.WATER) - ) { + if (fluidTypes?.length > 0 && fluidTypes?.includes(FluidType.WATER)) { return 3 - } else if ( - fluidTypes && - fluidTypes.length > 0 && - fluidTypes.includes(FluidType.GAS) - ) { + } else if (fluidTypes?.length > 0 && fluidTypes?.includes(FluidType.GAS)) { return 2 } else { return 1 diff --git a/src/utils/matomoTracker.ts b/src/utils/matomoTracker.ts index 1afb34486aa3badd66f427661e23e9ef838ed56b..5de0aad9e3b474075ca1e47b72600cd030d2e662 100644 --- a/src/utils/matomoTracker.ts +++ b/src/utils/matomoTracker.ts @@ -70,7 +70,7 @@ export default class MatomoTracker { let cozyDomain let userId const root: any = document.querySelector('[role=application]') - if (root && root.dataset) { + if (root?.dataset) { cozyDomain = readCozyDataFromDOM('cozyDomain') } if (cozyDomain) {