From 7ae7799b5aef42da1bc9675c62d77e16d463c58a Mon Sep 17 00:00:00 2001
From: Yoan Vallet <yoan.vallet@gmail.com>
Date: Sun, 24 May 2020 19:49:45 +0200
Subject: [PATCH] feat: create OAuthKonnector functionnality

---
 docker/cozy-app-dev-with-app.sh               |  5 +
 .../KonnectorViewerContainer.tsx              |  2 +
 .../OAuthKonnector/OAuthKonnector.tsx         | 95 +++++++++++++++++++
 src/locales/en.json                           | 26 +++--
 src/services/konnectorService.ts              |  2 +-
 5 files changed, 120 insertions(+), 10 deletions(-)
 create mode 100644 src/components/ContentComponents/OAuthKonnector/OAuthKonnector.tsx

diff --git a/docker/cozy-app-dev-with-app.sh b/docker/cozy-app-dev-with-app.sh
index 773506055..e55e182b6 100644
--- a/docker/cozy-app-dev-with-app.sh
+++ b/docker/cozy-app-dev-with-app.sh
@@ -216,9 +216,14 @@ do_install_app() {
           echo "Removing egl-api-connector..."
           cozy-stack konnectors uninstall egl-api-connector
   fi
+  if cozy-stack konnectors ls | grep 'enedis-konnector'; then
+          echo "Removing enedis-konnector..."
+          cozy-stack konnectors uninstall enedis-konnector
+  fi
   cozy-stack konnectors install enedis-scraping-connector file:///data/cozy_konnectors/enedis-scraping-connector-build
   cozy-stack konnectors install grdf-scraping-connector file:///data/cozy_konnectors/grdf-scraping-connector-build
   cozy-stack konnectors install egl-api-connector file:///data/cozy_konnectors/egl-api-connector-build
+  cozy-stack konnectors install enedis-konnector file:///data/cozy_konnectors/enedis-konnector-build
 }
 
 wait_for() {
diff --git a/src/components/ContainerComponents/KonnectorViewerContainer/KonnectorViewerContainer.tsx b/src/components/ContainerComponents/KonnectorViewerContainer/KonnectorViewerContainer.tsx
index a6f72bd43..56187b123 100644
--- a/src/components/ContainerComponents/KonnectorViewerContainer/KonnectorViewerContainer.tsx
+++ b/src/components/ContainerComponents/KonnectorViewerContainer/KonnectorViewerContainer.tsx
@@ -3,6 +3,7 @@ import { translate } from 'cozy-ui/react/I18n'
 import FluidConfigService from 'services/fluidConfigService'
 import IFluidConfig from 'services/IFluidConfig'
 import KonnectorViewerList from 'components/ContentComponents/KonnectorViewer/KonnectorViewerList'
+import OAuthKonnector from 'components/ContentComponents/OAuthKonnector/OAuthKonnector'
 
 interface KonnectorViewerContainerProps {
   isParam: boolean
@@ -22,6 +23,7 @@ const KonnectorViewerContainer: React.FC<KonnectorViewerContainerProps> = ({
         </div>
         <KonnectorViewerList isParam={isParam} fluidConfigs={fluidConfigs} />
       </div>
+      <OAuthKonnector />
     </div>
   )
 }
diff --git a/src/components/ContentComponents/OAuthKonnector/OAuthKonnector.tsx b/src/components/ContentComponents/OAuthKonnector/OAuthKonnector.tsx
new file mode 100644
index 000000000..089b09b5d
--- /dev/null
+++ b/src/components/ContentComponents/OAuthKonnector/OAuthKonnector.tsx
@@ -0,0 +1,95 @@
+import React, { useState, useEffect } from 'react'
+import { Client, withClient } from 'cozy-client'
+import { translate } from 'cozy-ui/react/I18n'
+
+import { Konnector } from 'doctypes'
+
+import KonnectorService from 'services/konnectorService'
+
+import { OAuthForm } from 'cozy-harvest-lib/dist/components/OAuthForm'
+import { OAuthWindow } from 'cozy-harvest-lib/dist/components/OAuthWindow'
+
+import triggersMutations from 'cozy-harvest-lib/dist/connections/triggers'
+import StyledButton from 'components/CommonKit/Button/StyledButton'
+
+interface OAuthKonnectorProps {
+  // account: any
+  // konnector: any
+  client: Client
+  t: Function
+}
+
+const OAuthKonnector: React.FC<OAuthKonnectorProps> = ({
+  client,
+  t,
+}: OAuthKonnectorProps) => {
+  const konnectorId = 'enedis-konnector'
+  const IDLE = 'idle'
+  const WAITING = 'waiting'
+
+  const [konnector, setKonnector] = useState<any>(null)
+  const [initialValues, setInitialValues] = useState<any>(null)
+  const [status, setStatus] = useState<string>(IDLE)
+
+  function endOAuth() {
+    setStatus(IDLE)
+  }
+  function startOAuth() {
+    setStatus(WAITING)
+  }
+  function handleAccountId(accountId) {
+    // const { onSuccess } = this.props
+    endOAuth()
+    // if (typeof onSuccess === 'function') onSuccess(accountId)
+  }
+  function handleSubmit() {
+    startOAuth()
+  }
+  function handleOAuthCancel() {
+    endOAuth()
+  }
+
+  useEffect(() => {
+    let subscribed = true
+    const konnectorService = new KonnectorService(client, konnectorId)
+
+    async function getKonnector() {
+      const _konnector: Konnector = await konnectorService.fetchKonnector()
+      if (!_konnector || !_konnector.slug) {
+        throw new Error(`Could not find konnector for ${konnectorId}`)
+      }
+      if (subscribed && _konnector) {
+        setKonnector(_konnector)
+      }
+    }
+    getKonnector()
+    return () => {
+      subscribed = false
+    }
+  }, [])
+
+  const isWaiting = status === WAITING
+  return !konnector ? null : (
+    <>
+      <StyledButton
+        type="button"
+        color="primary"
+        onClick={handleSubmit}
+        disabled={isWaiting}
+      >
+        {t('oauth.connect.label')}
+      </StyledButton>
+      {isWaiting && (
+        <OAuthWindow
+          client={client}
+          konnector={konnector}
+          onSuccess={handleAccountId}
+          onCancel={handleOAuthCancel}
+          t={t}
+        />
+      )}
+    </>
+  )
+}
+
+export default translate()(withClient(OAuthKonnector))
diff --git a/src/locales/en.json b/src/locales/en.json
index eef1f870d..d009fd664 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -36,7 +36,7 @@
     "APP_ONGOING_CHALLENGE_TITLE": "Défi en cours",
     "APP_FINISHED_CHALLENGE_TITLE": "Défi terminé"
   },
-  "LOADING":{
+  "LOADING": {
     "INDEX": "Vérification des données",
     "DATA": "Initialisation des données",
     "FLUIDTYPES": "Récupération de votre configuration",
@@ -137,7 +137,7 @@
     "START": "Allons-y !",
     "NOT_NOW": "Pas maintenant !",
     "STOP": "Arrêter le défi",
-    "BACK":"I'll be back",
+    "BACK": "I'll be back",
     "ECOGESTURE": "Voir l'écogeste",
     "LINKED_ECOGESTURES": "Écogestes associés",
     "VIEW_START": "Visualisation à partir du ",
@@ -161,13 +161,21 @@
     "NO_ECOGESTURE": "Pas d'ecogeste"
   },
   "NEGAWATT": {
-    "TITLE_NEGAWATT" : "NégaWatt",
-    "QUESTION" : "Que sont les nWh ? (néga Watt heure)",
-    "ANSWER" : {
-      "BASE" : "Le néga Watt heure (ou nWh) sert d'unité de mesure de vos économies d'énergie.",
-      "STRONG" : "10 nWh : économie importante",
-      "MEDIUM" : "3 nWh : économie moyenne",
-      "WEAK" : "1 nWh : économie faible"
+    "TITLE_NEGAWATT": "NégaWatt",
+    "QUESTION": "Que sont les nWh ? (néga Watt heure)",
+    "ANSWER": {
+      "BASE": "Le néga Watt heure (ou nWh) sert d'unité de mesure de vos économies d'énergie.",
+      "STRONG": "10 nWh : économie importante",
+      "MEDIUM": "3 nWh : économie moyenne",
+      "WEAK": "1 nWh : économie faible"
+    }
+  },
+  "oauth": {
+    "connect": {
+      "label": "Connect"
+    },
+    "window": {
+      "title": "OAuth"
     }
   }
 }
diff --git a/src/services/konnectorService.ts b/src/services/konnectorService.ts
index 4f956e5fd..b2521df2e 100644
--- a/src/services/konnectorService.ts
+++ b/src/services/konnectorService.ts
@@ -23,7 +23,7 @@ export default class KonnectorService {
     try {
       const { data } = await this._client.query(
         this._client.find(KONNECTORS_DOCTYPE).where({
-          _id: this._konnectorId,
+          _id: KONNECTORS_DOCTYPE + '/' + this._konnectorId,
         })
       )
       const konnector: Konnector = data && data[0]
-- 
GitLab