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/package.json b/package.json index 786e3e12bfd57ecafc82f7ea82c1f9669d5753fe..c2f6d49581e64608ff04b5ca63a2276d7274a266 100644 --- a/package.json +++ b/package.json @@ -2,32 +2,32 @@ "name": "ecolyo", "version": "1.10.0", "scripts": { - "tx": "tx pull --all || true", - "lint": "yarn lint:js", - "lint:js": "cs lint {src,test}/**/*.{js,jsx,ts,tsx} --fix", - "prebuild": "yarn lint", + "build": "yarn run build:css && yarn run build:browser", + "build:browser": "cs build --browser ", "build:cs": "build:browser", + "build:css": "sass -c ./src/styles", + "build-dev": "yarn run build:css && yarn run build-dev:browser", "build-dev:browser": "cs build --browser --config app.config.alpha.js", "build-dev:mobile": "cs build --mobile --config app.config.alpha.js", - "build:browser": "cs build --browser ", "build:mobile": "cs build --mobile", - "watch": "yarn watch:browser", - "watch:browser": "cs start --browser", - "watch:mobile": "cs watch --mobile", - "start:cs": "cs start --hot --browser --no-stack ", + "cozyPublish": "git fetch origin ${DEPLOY_BRANCH:-build}:${DEPLOY_BRANCH:-build} && cs publish --token $REGISTRY_TOKEN --build-commit $(git rev-parse ${DEPLOY_BRANCH:-build})", "deploy": "git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build}", "deploy-dev": "git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build-dev}", "deploy-test": "git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build-test} --repo=${DEPLOY_REPOSITORY:-https://forge.grandlyon.com/web-et-numerique/llle_project/ecolyo.git}", - "test": "cs test --verbose --coverage", - "cozyPublish": "git fetch origin ${DEPLOY_BRANCH:-build}:${DEPLOY_BRANCH:-build} && cs publish --token $REGISTRY_TOKEN --build-commit $(git rev-parse ${DEPLOY_BRANCH:-build})", - "build:css": "sass -c ./src/styles", - "start": "npm-run-all -p start:cs", - "build": "yarn run build:css && yarn run build:browser", - "build-dev": "yarn run build:css && yarn run build-dev:browser", - "release": "standard-version --no-verify", + "lint": "yarn lint:js", + "lint:js": "cs lint {src,test}/**/*.{js,jsx,ts,tsx} --fix", "load-data": "cd test && importData.bat", + "prebuild": "yarn lint", + "prepare": "husky install", + "release": "standard-version --no-verify", + "start": "npm-run-all -p start:cs", + "start:cs": "cs start --hot --browser --no-stack ", "start-stack": "cs start --hot --browser --stack", - "prepare": "husky install" + "test": "cs test --verbose --coverage", + "tx": "tx pull --all || true", + "watch": "yarn watch:browser", + "watch:browser": "cs start --browser", + "watch:mobile": "cs watch --mobile" }, "repository": { "type": "git", @@ -99,7 +99,7 @@ "@typescript-eslint/eslint-plugin": "^5.30.0", "@typescript-eslint/parser": "^5.30.0", "babel-polyfill": "^6.26.0", - "babel-preset-cozy-app": "1.12.0", + "babel-preset-cozy-app": "2.0.2", "copy-webpack-plugin": "6.4.1", "cozy-app-publish": "^0.30.0", "cozy-jobs-cli": "^1.13.6", diff --git a/scripts/createConnections.js b/scripts/createConnections.js index 6a582108f8a645bcf83e5c4d4cdb98c9f478a64f..ab05e05b460318901ea5bdfbcc80ec71749b65c3 100644 --- a/scripts/createConnections.js +++ b/scripts/createConnections.js @@ -134,15 +134,14 @@ async function launch() { // Enedis await axios({ method: 'put', - url: - 'http://cozy.tools:8080/data/io.cozy.accounts/88e68b8450cee09fe2f077610901094d', + url: 'http://cozy.tools:8080/data/io.cozy.accounts/88e68b8450cee09fe2f077610901094d', headers: headers, data: dataEnedisAccount, }) - .then(function(response) { + .then(function (response) { console.log(JSON.stringify(response.data)) }) - .catch(function(error) { + .catch(function (error) { console.log(error) }) @@ -152,25 +151,24 @@ async function launch() { headers: headers, data: dataEnedisTrigger, }) - .then(function(response) { + .then(function (response) { console.log(JSON.stringify(response.data)) }) - .catch(function(error) { + .catch(function (error) { console.log(error) }) // GRDF await axios({ method: 'put', - url: - 'http://cozy.tools:8080/data/io.cozy.accounts/89e68b8450cee09fe2f077610901094d', + url: 'http://cozy.tools:8080/data/io.cozy.accounts/89e68b8450cee09fe2f077610901094d', headers: headers, data: dataGrdfAccount, }) - .then(function(response) { + .then(function (response) { console.log(JSON.stringify(response.data)) }) - .catch(function(error) { + .catch(function (error) { console.log(error) }) @@ -180,25 +178,24 @@ async function launch() { headers: headers, data: dataGrdfTrigger, }) - .then(function(response) { + .then(function (response) { console.log(JSON.stringify(response.data)) }) - .catch(function(error) { + .catch(function (error) { console.log(error) }) // EGL await axios({ method: 'put', - url: - 'http://cozy.tools:8080/data/io.cozy.accounts/90e68b8450cee09fe2f077610901094d', + url: 'http://cozy.tools:8080/data/io.cozy.accounts/90e68b8450cee09fe2f077610901094d', headers: headers, data: dataEglAccount, }) - .then(function(response) { + .then(function (response) { console.log(JSON.stringify(response.data)) }) - .catch(function(error) { + .catch(function (error) { console.log(error) }) @@ -208,10 +205,10 @@ async function launch() { headers: headers, data: dataEglTrigger, }) - .then(function(response) { + .then(function (response) { console.log(JSON.stringify(response.data)) }) - .catch(function(error) { + .catch(function (error) { console.log(error) }) } diff --git a/src/components/Analysis/AnalysisConsumption.tsx b/src/components/Analysis/AnalysisConsumption.tsx index 83fc2cfc6267fbc864b647591648d6e986906d36..622af99b6b4ea4746430fad728a6080ea1fe4b9a 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]) } } @@ -212,8 +212,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 644dcd3fab609c92cc504179649b0d3e17b07b38..712283338269cd52f1cc3fc83a48ec4b6c7d34af 100644 --- a/src/components/Analysis/ElecHalfHourMonthlyAnalysis.tsx +++ b/src/components/Analysis/ElecHalfHourMonthlyAnalysis.tsx @@ -96,7 +96,7 @@ const ElecHalfHourMonthlyAnalysis: React.FC< aggegatedDate.year, aggegatedDate.month ) - if (subscribed && data && data.length) { + if (subscribed && data?.length) { const aggregatedData = emas.aggregateValuesToDataLoad(data[0]) setenedisAnalysisValues(data[0]) setMonthDataloads(aggregatedData) @@ -220,7 +220,7 @@ const ElecHalfHourMonthlyAnalysis: React.FC< <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 4f7287762b7246b6a910a68bf6a061dadefa2b96..94e0b0b6e15183bafca04028e2cb0c69b2c73447 100644 --- a/src/components/Analysis/MonthlyAnalysis.tsx +++ b/src/components/Analysis/MonthlyAnalysis.tsx @@ -76,10 +76,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/Charts/UncomingBar.tsx b/src/components/Charts/UncomingBar.tsx index d255d9612610beda91c4d08076623b2f75ef1018..e669a5d07332862e775fade1c031464585c7361b 100644 --- a/src/components/Charts/UncomingBar.tsx +++ b/src/components/Charts/UncomingBar.tsx @@ -30,9 +30,9 @@ const UncomingBar = ({ const barClass = animationEnded ? `bar-UNCOMING ` - : `bar-UNCOMING bounce-${ - browser && browser.name !== 'edge' ? '1' : '3' - } delay--${index % 13}` + : `bar-UNCOMING bounce-${browser?.name !== 'edge' ? '1' : '3'} delay--${ + index % 13 + }` const getBandWidth = (): number => { return xScale.bandwidth() diff --git a/src/components/CommonKit/Card/StyledIconCard.tsx b/src/components/CommonKit/Card/StyledIconCard.tsx index b8067e8b7f318992f21e62f40ffea50d7c63dc4e..b5b087ad3f39ba87e7758706c6581cb02e6216a4 100644 --- a/src/components/CommonKit/Card/StyledIconCard.tsx +++ b/src/components/CommonKit/Card/StyledIconCard.tsx @@ -62,7 +62,7 @@ const GenerateContentCard = ( spacing={8} direction="column" alignItems="center" - justify="center" + justifyContent="center" > <Grid item> <StyledIcon icon={icon} size={64} /> @@ -100,7 +100,12 @@ const StyledIconCard: React.ComponentType<StyledIconCardProps> = ({ return ( <CardBase {...props}> <CardContentBase> - <Grid container spacing={8} alignItems="center" justify="center"> + <Grid + container + spacing={8} + alignItems="center" + justifyContent="center" + > <Grid item>{props.children}</Grid> </Grid> </CardContentBase> diff --git a/src/components/Connection/ConnectionResult.tsx b/src/components/Connection/ConnectionResult.tsx index d24a9512e494e5546809e58163c9570284330b65..b8e082d1f44dc075835ca53d5d45efde72562869 100644 --- a/src/components/Connection/ConnectionResult.tsx +++ b/src/components/Connection/ConnectionResult.tsx @@ -117,10 +117,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 ) @@ -129,9 +126,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( @@ -216,9 +212,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 38251f47a1f45160ba09fc5ce83354b676a330a8..3d2f9674e67d63f5bf8c4621194ecc0113d8b9fb 100644 --- a/src/components/Connection/FormLogin.tsx +++ b/src/components/Connection/FormLogin.tsx @@ -150,7 +150,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/Ecogesture/EcogestureModal.tsx b/src/components/Ecogesture/EcogestureModal.tsx index 1ea598db980a17a795365d9bd56faa8dfe97752a..d7b06ff987b09e40da4f8eaea18df36ecd3190be 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 1b5f7e7985a3d339b37a43a7934fdbf9e26edf22..d5dad471b750d687e8b8396bc510e18e468ef3d6 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), @@ -60,7 +59,7 @@ const SingleEcogesture: React.FC<SingleEcogestureProps> = ({ } const [, setValidExploration] = useExploration() const toggleMoreDetail = () => { - setIsMoreDetail((prev) => !prev) + setIsMoreDetail(prev => !prev) } const toggleObjective = useCallback(async () => { if (ecogesture) { @@ -69,7 +68,7 @@ const SingleEcogesture: React.FC<SingleEcogestureProps> = ({ toUpdate ) if (updatedEcogesture) { - setIsObjective((prev) => !prev) + setIsObjective(prev => !prev) setEcogesture(updatedEcogesture) } } @@ -82,7 +81,7 @@ const SingleEcogesture: React.FC<SingleEcogestureProps> = ({ toUpdate ) if (updatedEcogesture) { - setIsDoing((prev) => !prev) + setIsDoing(prev => !prev) setEcogesture(updatedEcogesture) } } 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 ac64219d36b8a0a79c44dc362d81e60942594350..43fae72cd5aeadb5f885a2e12451a1f52effdf6d 100644 --- a/src/components/Home/ConsumptionView.tsx +++ b/src/components/Home/ConsumptionView.tsx @@ -110,8 +110,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 c0e14b19c0704659906fdda1954122bf0dde4693..5d72b8a292ee47304ffb81d58932c32b30bca018 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 c3f19abf018095c5df960ba48c8c7fdd5185c324..470ab679a1ed35d9b47454d8d6d23191bf44b1bf 100644 --- a/src/components/Konnector/KonnectorViewerCard.tsx +++ b/src/components/Konnector/KonnectorViewerCard.tsx @@ -131,7 +131,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 } } @@ -144,9 +144,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 { updatedUserChallenge, dataloads } = diff --git a/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx b/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx index b5f3f51601a5e3044dc8704a2e217d9ddbd154a7..50a77b3aea7b98b7cb317239859587ed77612122 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 - ? 'positive' - : 'negative' + 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 e9df3d07bee2348c36219eb3d9c40da781de5780..d4bf98789eecedaaa5b215ba2f34fc9cac53b734 100644 --- a/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx +++ b/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx @@ -33,22 +33,18 @@ const PerformanceIndicatorContent: React.FC< }: 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 24832b694861de70e83e7578e9ef7465a728ff66..b71f51309fb3c514080a8c068197d520e2af3d15 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 9beb6cac6acdc54f0d3d45ac5383d72827928bc0..3db7ec06dd8dc8ef7969edfef773979b200ad6e6 100644 --- a/src/components/Splash/SplashRoot.tsx +++ b/src/components/Splash/SplashRoot.tsx @@ -195,17 +195,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 = @@ -218,9 +216,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)) } @@ -228,8 +225,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, dataloads } = await initializationService.initDuelProgress( @@ -289,7 +286,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 9c86319a2757444fb967a71373b1956e4f80574f..f813c6dfe11a40a5e81f47569dce5b0748224382 100644 --- a/src/services/account.service.ts +++ b/src/services/account.service.ts @@ -73,9 +73,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 ddcac6f746b07b351f96fcdc7df2fb058db9ba51..f08afb593d08dbcc00a9aa2489594f27f4932cee 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 60e381a5ec5b979ea0c9e3403c64721aef0198f2..cdb594de248c046f0e8dc517a550da1ca6f08cfc 100644 --- a/src/services/consumption.service.ts +++ b/src/services/consumption.service.ts @@ -134,7 +134,7 @@ export default class ConsumptionDataManager { compareMaxTimePeriod, isHome ) - return allData && allData.actualData + return allData?.actualData ? Math.max(...allData.actualData.map(d => d.value)) : 0 } else { @@ -375,7 +375,7 @@ export default class ConsumptionDataManager { fluideType, timeStep ) - if (queryResult && queryResult.data.length > 0) { + if (queryResult?.data.length > 0) { return true } return false @@ -404,7 +404,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 817eac1b6677e1454cd95876aa570148a1cb9760..867b53c8eecee4d72ecbcc8d04701aba002085ae 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 c7724830513e8555585bad28d826c9ca929cf836..69800a4d508587701fbd9927f6843ff5a6dfcd72 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: @@ -152,8 +152,7 @@ export default class FluidService { { fluidType: FluidType.ELECTRICITY, status: - partnersInfo && - partnersInfo.notification_activated && + partnersInfo?.notification_activated && this.isFluidInPartnerIssue( FluidType.ELECTRICITY, this.parseFluidStatus(elecKonnector, elecStatus), @@ -176,8 +175,7 @@ export default class FluidService { { fluidType: FluidType.WATER, status: - partnersInfo && - partnersInfo.notification_activated && + partnersInfo?.notification_activated && this.isFluidInPartnerIssue( FluidType.WATER, this.parseFluidStatus(waterKonnector, waterStatus), @@ -200,8 +198,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 d154d1f88bcb7d1423b8c8d5ab8d4b010d343f22..77553f5021d696eebf4cde7855088794ea63ca98 100644 --- a/src/services/initialization.service.ts +++ b/src/services/initialization.service.ts @@ -235,10 +235,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) { @@ -246,10 +243,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' @@ -285,10 +279,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' @@ -312,7 +303,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 { @@ -356,10 +347,7 @@ export default class InitializationService { // 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) { @@ -367,10 +355,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' @@ -396,10 +381,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' @@ -424,7 +406,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) { @@ -432,10 +414,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' @@ -461,10 +440,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' @@ -489,10 +465,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) { @@ -500,10 +473,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' @@ -530,10 +500,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' @@ -559,10 +526,7 @@ export default class InitializationService { // 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) { @@ -572,7 +536,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( @@ -601,7 +565,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 c21fcb52c24744a257fdacca5c0c45d8dbcb1943..59d7f2555464b772e65e62043c98ba7e7a3b6fec 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 7a6ad0e4e6bdbd2787a33aab9f05a4ca14fe0a7c..4df247207173205cb1fabd42bc7af6dfbdab6b0e 100644 --- a/src/services/queryRunner.service.ts +++ b/src/services/queryRunner.service.ts @@ -319,7 +319,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 @@ -375,7 +375,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) { @@ -392,12 +392,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, @@ -416,12 +413,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 e67f12d15ebbf9c88f22a3210a13589b8c3f9480..a44dd35faa96fe8da5afc0a3cc8e4ebc24246e21 100644 --- a/src/services/quiz.service.ts +++ b/src/services/quiz.service.ts @@ -428,7 +428,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) { @@ -461,12 +461,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 = { @@ -487,7 +482,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 11b578dd1307498fc755385fce6ee981bd818afe..d4cfd9539aee7a5d79bdcd8bb38fa0e0d7425f1c 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 c1cc3e14f09ba8ede239372b4e222621bb233b13..c9473a704dc67b98b1bbe708fc16b2106ec3189b 100644 --- a/src/targets/services/aggregatorUsageEvents.ts +++ b/src/targets/services/aggregatorUsageEvents.ts @@ -390,7 +390,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, }) @@ -398,43 +398,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 { @@ -447,11 +427,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) { @@ -674,7 +650,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, @@ -718,7 +694,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) } @@ -1114,7 +1090,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 6475330793078c4903710f9b870a5fda9969fa2e..d41bec8bbe2b79ae41b148c2ae8acd7e95a84513 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) { diff --git a/yarn.lock b/yarn.lock index c7f360240a34f1877c35fc9c99c5819359f505de..ed8369c37e4318b31efd504ba60cdc365f5ff208 100644 --- a/yarn.lock +++ b/yarn.lock @@ -47,6 +47,27 @@ resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.18.5.tgz#acac0c839e317038c73137fbb6ef71a1d6238471" integrity sha512-BxhE40PVCBxVEJsSBhB6UWyAuqJRxGsAw8BdHMJ3AKGydcwuWW4kOO3HmqBQAdcq/OP+/DlTVxLvsCzRTnZuGg== +"@babel/core@7.16.12": + version "7.16.12" + resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.16.12.tgz#5edc53c1b71e54881315923ae2aedea2522bb784" + integrity sha512-dK5PtG1uiN2ikk++5OzSYsitZKny4wOCD0nrO4TqnW4BVBTQ2NGS3NgilvT/TEyxTST7LNyWV/T4tXDoD3fOgg== + dependencies: + "@babel/code-frame" "^7.16.7" + "@babel/generator" "^7.16.8" + "@babel/helper-compilation-targets" "^7.16.7" + "@babel/helper-module-transforms" "^7.16.7" + "@babel/helpers" "^7.16.7" + "@babel/parser" "^7.16.12" + "@babel/template" "^7.16.7" + "@babel/traverse" "^7.16.10" + "@babel/types" "^7.16.8" + convert-source-map "^1.7.0" + debug "^4.1.0" + gensync "^1.0.0-beta.2" + json5 "^2.1.2" + semver "^6.3.0" + source-map "^0.5.0" + "@babel/core@7.2.2": version "7.2.2" resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.2.2.tgz#07adba6dde27bb5ad8d8672f15fde3e08184a687" @@ -110,7 +131,7 @@ semver "^6.3.0" source-map "^0.5.0" -"@babel/eslint-parser@^7.17.0": +"@babel/eslint-parser@^7.16.3", "@babel/eslint-parser@^7.17.0": version "7.18.2" resolved "https://registry.yarnpkg.com/@babel/eslint-parser/-/eslint-parser-7.18.2.tgz#e14dee36c010edfb0153cf900c2b0815e82e3245" integrity sha512-oFQYkE8SuH14+uR51JVAmdqwKYXGRjEXx7s+WiagVjqQ+HPE+nnwyF2qlVG8evUsUHmPcA+6YXMEDbIhEyQc5A== @@ -2885,9 +2906,9 @@ pretty-format "^26.0.0" "@types/jest@^28.0.0": - version "28.1.3" - resolved "https://registry.yarnpkg.com/@types/jest/-/jest-28.1.3.tgz#52f3f3e50ce59191ff5fbb1084896cc0cf30c9ce" - integrity sha512-Tsbjk8Y2hkBaY/gJsataeb4q9Mubw9EOz7+4RjPkzD5KjTvHHs7cpws22InaoXxAVAhF5HfFbzJjo6oKWqSZLw== + version "28.1.4" + resolved "https://registry.yarnpkg.com/@types/jest/-/jest-28.1.4.tgz#a11ee6c8fd0b52c19c9c18138b78bbcc201dad5a" + integrity sha512-telv6G5N7zRJiLcI3Rs3o+ipZ28EnE+7EvF0pSrt2pZOMnAVI/f+6/LucDxOvcBcTeTL3JMF744BbVQAVBUQRA== dependencies: jest-matcher-utils "^28.0.0" pretty-format "^28.0.0" @@ -3958,22 +3979,6 @@ babel-polyfill@^6.26.0: core-js "^2.5.0" regenerator-runtime "^0.10.5" -babel-preset-cozy-app@1.12.0: - version "1.12.0" - resolved "https://registry.yarnpkg.com/babel-preset-cozy-app/-/babel-preset-cozy-app-1.12.0.tgz#dea97f3f3fb6ac18835613083b63b0b42a9e4909" - integrity sha512-PjVfCypMjFNzeii3qg+SJkRDGzX99s6Cj2mnOP4RseF0YjpLDAzPyg37j8rLAwYP5DvQGgt8vW/6hsWfnIdf8Q== - dependencies: - "@babel/core" "^7.12.3" - "@babel/helper-plugin-utils" "^7.10.4" - "@babel/plugin-proposal-class-properties" "^7.12.1" - "@babel/plugin-proposal-object-rest-spread" "^7.12.1" - "@babel/plugin-transform-runtime" "^7.12.1" - "@babel/preset-env" "^7.12.1" - "@babel/preset-react" "^7.12.5" - "@babel/runtime" "^7.12.5" - browserslist-config-cozy "^0.4.0" - lodash "^4.17.19" - babel-preset-cozy-app@1.9.2: version "1.9.2" resolved "https://registry.yarnpkg.com/babel-preset-cozy-app/-/babel-preset-cozy-app-1.9.2.tgz#eb072c931828b2cacf84fd8dac57f345b5b608d8" @@ -3990,6 +3995,25 @@ babel-preset-cozy-app@1.9.2: browserslist-config-cozy "^0.3.1" lodash "4.17.19" +babel-preset-cozy-app@2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/babel-preset-cozy-app/-/babel-preset-cozy-app-2.0.2.tgz#057da4ac68b1340a58cde18dbd40e67e04f3b998" + integrity sha512-D7+LE5zVDFhD9fxfhjERr2qxfxf+pc8w6RWe5mV/bS5Hz2iULNlScslg2Pbz+U5gHQtxysxmwQYz8ufjZmfFbg== + dependencies: + "@babel/core" "7.16.12" + "@babel/eslint-parser" "^7.16.3" + "@babel/helper-plugin-utils" "^7.14.5" + "@babel/plugin-proposal-class-properties" "^7.16.0" + "@babel/plugin-proposal-object-rest-spread" "^7.16.0" + "@babel/plugin-transform-runtime" "^7.16.4" + "@babel/preset-env" "^7.16.4" + "@babel/preset-react" "^7.16.0" + "@babel/preset-typescript" "^7.16.0" + "@babel/runtime" "^7.16.3" + browserslist-config-cozy "^0.4.0" + lodash "^4.17.21" + typescript "^4.5.2" + babel-preset-current-node-syntax@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz#b4399239b89b2a011f9ddbe3e4f401fc40cff73b" @@ -4957,9 +4981,9 @@ clone@^2.1.1: integrity sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18= clsx@^1.0.4: - version "1.1.1" - resolved "https://registry.yarnpkg.com/clsx/-/clsx-1.1.1.tgz#98b3134f9abbdf23b2663491ace13c5c03a73188" - integrity sha512-6/bPho624p3S2pMyvP5kKBPXnI3ufHLObBFCfgx+LkeR5lg2XYy2hqZqUf45ypD8COn2bhgGJSUE+l5dhNBieA== + version "1.2.0" + resolved "https://registry.yarnpkg.com/clsx/-/clsx-1.2.0.tgz#b0e415ea7537dbac01b169c5cec1caeb11d86566" + integrity sha512-EPRP7XJsM1y0iCU3Z7C7jFKdQboXSeHgEfzQUTlz7m5NP3hDrlz48aUsmNGp4pC+JOW9WA3vIRqlYuo/bl4Drw== co@^4.6.0: version "4.6.0" @@ -6856,7 +6880,7 @@ domhandler@^4.0, domhandler@^4.0.0, domhandler@^4.2.0, domhandler@^4.2.2: dependencies: domelementtype "^2.2.0" -domhandler@^5.0.1, domhandler@^5.0.2: +domhandler@^5.0, domhandler@^5.0.1, domhandler@^5.0.2: version "5.0.3" resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-5.0.3.tgz#cc385f7f751f1d1fc650c21374804254538c7d31" integrity sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w== @@ -7058,11 +7082,6 @@ entities@^2.0.0: resolved "https://registry.yarnpkg.com/entities/-/entities-2.2.0.tgz#098dc90ebb83d8dffa089d55256b351d34c4da55" integrity sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A== -entities@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/entities/-/entities-3.0.1.tgz#2b887ca62585e96db3903482d336c1006c3001d4" - integrity sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q== - entities@^4.2.0, entities@^4.3.0: version "4.3.1" resolved "https://registry.yarnpkg.com/entities/-/entities-4.3.1.tgz#c34062a94c865c322f9d67b4384e4169bcede6a4" @@ -8978,8 +8997,8 @@ html-to-react@^1.3.4: resolved "https://registry.yarnpkg.com/html-to-react/-/html-to-react-1.4.7.tgz#a58129c1b77c6d4e047a647372bd194e25420b89" integrity sha512-adtKiee5AtnuUhdB8bxbASRP2bW/A0OrlwysEuqZxXdURb0/1XR0m/woE1V5cJA1U5nyzAvk/PdFNO9S73DE/g== dependencies: - domhandler "^4.0" - htmlparser2 "^7.0" + domhandler "^5.0" + htmlparser2 "^8.0" lodash.camelcase "^4.3.0" ramda "^0.27.1" @@ -9037,17 +9056,7 @@ htmlparser2@^6.1.0: domutils "^2.5.2" entities "^2.0.0" -htmlparser2@^7.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-7.2.0.tgz#8817cdea38bbc324392a90b1990908e81a65f5a5" - integrity sha512-H7MImA4MS6cw7nbyURtLPO1Tms7C5H602LRETv95z1MxO/7CP7rDVROehUYeYBUYEON94NXXDEPmZuq+hX4sog== - dependencies: - domelementtype "^2.0.1" - domhandler "^4.2.2" - domutils "^2.8.0" - entities "^3.0.1" - -htmlparser2@^8.0.1: +htmlparser2@^8.0, htmlparser2@^8.0.1: version "8.0.1" resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-8.0.1.tgz#abaa985474fcefe269bc761a779b544d7196d010" integrity sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA== @@ -11973,9 +11982,9 @@ msgpack5@^4.0.2: readable-stream "^2.3.6" safe-buffer "^5.1.2" -"mui-bottom-sheet@https://github.com/cozy/mui-bottom-sheet.git#v1.0.6": +"mui-bottom-sheet@git+https://github.com/cozy/mui-bottom-sheet.git#v1.0.6": version "1.0.6" - resolved "https://github.com/cozy/mui-bottom-sheet.git#494c40416ecde95732c864f9b921e7e545075aa5" + resolved "git+https://github.com/cozy/mui-bottom-sheet.git#494c40416ecde95732c864f9b921e7e545075aa5" dependencies: "@juggle/resize-observer" "^3.1.3" jest-environment-jsdom-sixteen "^1.0.3" @@ -13580,9 +13589,9 @@ pseudomap@^1.0.2: integrity sha1-8FKijacOYYkX7wqKw0wa5aaChrM= psl@^1.1.24, psl@^1.1.28, psl@^1.1.33: - version "1.8.0" - resolved "https://registry.yarnpkg.com/psl/-/psl-1.8.0.tgz#9326f8bcfb013adcc005fdff056acce020e51c24" - integrity sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ== + version "1.9.0" + resolved "https://registry.yarnpkg.com/psl/-/psl-1.9.0.tgz#d0df2a137f00794565fcaf3b2c00cd09f8d5a5a7" + integrity sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag== public-encrypt@^4.0.0: version "4.0.3"