> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kleep.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Mobile - Android

**Dépôt :** [https://github.com/KlipFit/kleep-android](https://github.com/KlipFit/kleep-android)

## Installation

***

Cette procédure ne doit être suivie qu'une seule fois, lors de la première installation du SDK dans votre projet. Référez-vous à la section **Mise à jour** pour les instructions des mises à jour ultérieures.

1. Dans votre *gradle.properties,* ajoutez ce token :

   `authToken=jp_9ibcequhrjtge3cmavt2k4sq6a`

2. Dans votre *settings.gradle ou settings.gradle.kts*, ajoutez les lignes suivantes :

```groovy theme={null}
// for *settings.gradle*

dependencyResolutionManagement {
*// ...*
    repositories {
        *// ...*
~~~~        maven {
            url "https://jitpack.io"
            credentials { username authToken }
        }
    }
}
```

```kotlin theme={null}
// for *settings.gradle.kts*

*dependencyResolutionManagement {
// ...
    repositories {
	      // ... 
        maven {
            url = uri("https://jitpack.io")
            credentials(PasswordCredentials::class) {
                val authToken: String by settings
                username = authToken*
            }
        *}
    }
}*
```

1. Dans le fichier *build.gradle* ou *build.gradle.kts* de votre module, ajoutez les lignes suivantes pour créer la dépendance :

```groovy theme={null}
// *build.gradle*
dependencies {
	implementation 'com.github.KlipFit:kleep-android:version'
}
```

```kotlin theme={null}
// *build.gradle.kts*
dependencies {
	implementation("com.github.KlipFit:kleep-android:version")
}
```

## **Initialisation**

***

Modifiez votre classe `Application` personnalisée et fournissez `applicationContext` pour l'initialisation.

```kotlin theme={null}
import com.kleep.sdk.KleepResult
import com.kleep.sdk.Kleep

class CustomApplication: Application() {

    override fun onCreate() {
        super.onCreate()
        Kleep.init(applicationContext)
    }
}
```

N'oubliez pas d'ajouter votre classe Application dans **`Manifest.xml`**

```kotlin theme={null}
<application
        android:name=".CustomApplication"
        ...
        >
...
</application>
```

## Import

***

Vous pouvez importer manuellement le module au début de votre **`MainActivity.kt`**

```kotlin theme={null}
import com.kleep.sdk.KleepResult
import com.kleep.sdk.Kleep
```

## Utilisation

***

Le SDK est livré avec 3 méthodes :

| méthode                        | temps de chargement       |
| ------------------------------ | ------------------------- |
| `show`                         | Premier lancement : 250ms |
| Lancements suivants : 50-250ms |                           |
| `requestSize`                  | 250ms                     |
| `track`                        | 250ms                     |

### Méthode 1 : `requestSize`

Cette méthode permet d'implémenter la logique du CTA.

**Schéma logique**

Ce schéma explique comment mettre à jour le CTA ouvrant Kleep.

[https://www.figma.com/board/BlurZ01lR3JBQZeTUU98TE/Mobile---CTA-Logic?node-id=0-1\&t=ccXWciNziIdfhgew-1](https://www.figma.com/board/BlurZ01lR3JBQZeTUU98TE/Mobile---CTA-Logic?node-id=0-1\&t=ccXWciNziIdfhgew-1)

**Exemple d'implémentation**

```kotlin theme={null}
Kleep.builder(this, onResult = {
	when (it) {
	    is KleepResult.NotSupported -> {
	        // Handle the NotSupported case
	    }
	
	    is KleepResult.NoRecommendationYet -> {
	        // Handle the NoRecommendationYet case
	    }
	
	    is KleepResult.RecommendationFound -> {
	        val resultText = it.size
	        val variantId = it.variantId
	        Toast.makeText(this, resultText, Toast.LENGTH_SHORT).show()         
      }

      else -> {

      }
    }
})
	.setPackageName(packageName)         // optional
	.setLang(DEFAULT_LANGUAGE)           // required: "fr", "en", "es", "it", "pt", "nl"
	.setProductId("1234")                // required
	.setRetailer("retailer_name")        // required
	.setTrackingId("uuid")               // empty if non-existent 
	.setCustomerId("unique_customer_id") // optional
	.requestSize()
```

```kotlin theme={null}
package com.kleep.sdk

/**
 * Interface with the Kleep SDK in order to compute the recommended size of a product given some user information
 */
interface KleepDialogBuilder {
    /**
     * Set the package name, not required
     * @return interface of the SDK builder
     */
    fun setPackageName(packageName: String): KleepDialogBuilder
    
    /**
     * Set the language to use: required (default to FR)
     * Values supported: "fr", "en", "es", "it", "pt", "nl"
     * @return interface of the SDK builder
     */
    fun setLang(lang: String): KleepDialogBuilder

    /**
     * Set product ID, required to compute the recommended size.
     * @return interface of the SDK builder
     */
    fun setProductId(productId: String): KleepDialogBuilder

    /**
     * Set tracking id, required. Should represent unique tracking id.
     * Should be an empty string if the tracking id does not exist.
     *
     * @return interface of the SDK builder
     */
    fun setTrackingId(tracking_id: String): KleepDialogBuilder

    /**
     * Set customer id, optonal. Should represent customer id linked to backend.
     * Should be an empty string if the tracking id does not exist.
     *
     * @return interface of the SDK builder
     */
    fun setCustomerId(customer_id: String): KleepDialogBuilder
    
    /**
     * Set retail name (mandatory), required for stock/similar_products requests.
     *
     * @return interface of the SDK builder
     */
    fun setRetailer(retailerName: String): KleepDialogBuilder
    
    /**
     * Sets the stock availability for items.
     * Providing an empty map or omitting this function disables stock checking.
     *
     * @return interface of the SDK builder
     */
    fun setStocks(stocks: Map<String, Boolean>): KleepDialogBuilder

    /**
     * Display the Kleep UI inside a BottomSheet, so the user can fill a survey or take 2 pictures
     * in order to compute and display the recommended size to the user
     */
    fun show()

    /**
     * Get the latest recommended size for the last viewed user.
     * As it's an async process and take several seconds,
		 * the result will be give by the onResult listener , provided to the SDK builder
     */
    fun requestSize()
}
```

### Méthode 2 : `show`

Cette méthode est appelée lorsque le CTA est cliqué. Elle permet de charger les différents écrans. **Le développeur intégrant le SDK doit les intégrer dans une bottom sheet.**

| paramètre                                                                                                                   | priorité    | description                                                            |
| --------------------------------------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| **productID**                                                                                                               | *requis*    | L'identifiant de votre produit                                         |
| **retailer**                                                                                                                | *requis*    | Nom du revendeur                                                       |
| **customerID**                                                                                                              | *optionnel* | Identifiant CRM, utilisé pour les analytics                            |
| **trackingID**                                                                                                              | *optionnel* | Identifiant utilisé par le fournisseur de tracking externe             |
| stocks                                                                                                                      | *optionnel* | Une map d'identifiants de variantes d'articles à leur statut de stock. |
| `true` pour en stock, `false` (par défaut) pour en rupture de stock, emptyMap ou non spécifié pour ignorer la vérification. |             |                                                                        |

```kotlin theme={null}
Kleep.builder(this, onResult = {
	when (it) {
	    is KleepResult.NotSupported -> {
	        // Handle the NotSupported case
	    }
	
	    is KleepResult.NoRecommendationYet -> {
	        // Handle the NoRecommendationYet casem
	    }
	
	    is KleepResult.RecommendationFound -> {
	        val resultText = it.size
	        val variantId = it.variantId
	        // addToCart(variantId)
	        
	        Toast.makeText(this, resultText, Toast.LENGTH_SHORT).show()
      }

      else -> {

      }
    }
})
	.setPackageName(packageName)         // optional
	.setLang(DEFAULT_LANGUAGE)           // required: "fr", "en", "es", "it", "pt", "nl"
	.setProductId("1234")                // required
	.setRetailer("retailer_name")        // required
	.setTrackingId("tracking_id")        // optional
	.setCustomerId("unique_customer_id") // optional
	.setStocks(stocks: Map<String, Boolean>) // optional
	.show()
```

### Méthode 3 : `track`

Cette méthode permet de tracker des événements personnalisés.

```kotlin theme={null}
Kleep.track(eventName: String, eventInfo: Map<String, String>)
```

Nous souhaitons tracker 3 événements :

| eventName               | Déclencheur                                  |
| ----------------------- | -------------------------------------------- |
| `product_viewed`        | À la consultation de la PDP                  |
| `product_added_to_cart` | À l'ajout au panier                          |
| `checkout_completed`    | À la confirmation de commande après paiement |

**`product_viewed`**

[Paramètres (CSV)](/images/android/Untitled%202c68bfd3e84981db82a9f924cf43673d.csv)

**Exemple**

```jsx theme={null}
{
		productId: str
}
```

**`product_added_to_cart`**

[Paramètres (CSV)](/images/android/Untitled%202c68bfd3e8498100baf9d17e8b7df5e0.csv)

**Exemple**

```jsx theme={null}
{
    productId: str,
    variantId: str,
    cart: [
	    {
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
				sku: "XYZ",
		    size: "S",
		    quantity: 2,
		    price: {
						amount: "50",
				    currencyCode: "EUR"		    
		    }
	    },
	    {
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
		    sku: "XYZ",
		    size: "S",
		    quantity: 1,
		    price: {
				    amount: "40",
				    currencyCode: "USD"
				}
	    }
	    ...
    ],
}
```

**`checkout_completed`**

[Paramètres (CSV)](/images/android/Untitled%202c68bfd3e84981b0bdecd417ba621e4e.csv)

**Exemple**

```jsx theme={null}
{
    orderId: "000001",
    cart: [
	    {
		    lineItemId: "000001#1",
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
				sku: "XYZ",
		    size: "S",
		    quantity: 2,
		    price: {
						amount: "50",
				    currencyCode: "EUR"		    
		    }
	    },
	    {
			  lineItemId: "000000#2",
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
		    sku: "XYZ",
		    size: "S",
		    quantity: 1,
		    price: {
				    amount: "40",
				    currencyCode: "USD"
				}
	    }
	    ...
    ],
}
```
