> ## 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 Móvil - Android

**Repositorio:** [https://github.com/KlipFit/kleep-android](https://github.com/KlipFit/kleep-android)

## Instalación

***

Este proceso solo debe seguirse una vez, la primera vez que necesites instalar el SDK en tu proyecto. Consulta la sección **Actualización** para ver las instrucciones de actualizaciones posteriores.

1. En tu *gradle.properties,* añade este token:

   `authToken=jp_9ibcequhrjtge3cmavt2k4sq6a`

2. En tu *settings.gradle o settings.gradle.kts*, añade las siguientes líneas:

```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. En el archivo *build.gradle* o *build.gradle.kts* de tu módulo, añade las siguientes líneas para crear la dependencia:

```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")
}
```

## **Inicialización**

***

Edita tu clase `Application` personalizada y proporciona `applicationContext` para la inicialización.

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

class CustomApplication: Application() {

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

No olvides añadir tu clase Application a **`Manifest.xml`**

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

## Importar

***

Puedes importar manualmente el módulo al principio de tu **`MainActivity.kt`**

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

## Uso

***

El SDK incluye 3 métodos:

| método                           | tiempo de carga          |
| -------------------------------- | ------------------------ |
| `show`                           | Primera ejecución: 250ms |
| Siguientes ejecuciones: 50-250ms |                          |
| `requestSize`                    | 250ms                    |
| `track`                          | 250ms                    |

### Método 1: `requestSize`

Este método permite implementar la lógica del CTA.

**Esquema lógico**

Este esquema explica cómo actualizar el CTA que abre 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)

**Ejemplo de implementación**

```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étodo 2: `show`

Este método se llama cuando se hace clic en el CTA. Permite cargar las diferentes pantallas. **El desarrollador que integra el SDK debe embebidos en un bottom sheet.**

| parámetro      | prioridad     | descripción                                                                                                                                                                      |
| -------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **productID**  | *obligatorio* | El ID de tu producto                                                                                                                                                             |
| **retailer**   | *obligatorio* | Nombre del comerciante                                                                                                                                                           |
| **customerID** | *opcional*    | Identificador CRM, usado para analíticas                                                                                                                                         |
| **trackingID** | *opcional*    | ID usado por el proveedor de seguimiento externo                                                                                                                                 |
| stocks         | *opcional*    | Un mapa de IDs de variante de artículo a su estado de stock. `true` para en stock, `false` (por defecto) para sin stock, emptyMap o no especificado para omitir la verificación. |

```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étodo 3: `track`

Este método permite rastrear eventos personalizados.

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

Queremos rastrear 3 eventos:

| eventName               | Disparador                                       |
| ----------------------- | ------------------------------------------------ |
| `product_viewed`        | Al visualizar la PDP                             |
| `product_added_to_cart` | Al añadir producto al carrito                    |
| `checkout_completed`    | Tras la confirmación del pedido después del pago |

**`product_viewed`**

[Parámetros (CSV)](/images/android/Untitled%202c68bfd3e84981db82a9f924cf43673d.csv)

**Ejemplo**

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

**`product_added_to_cart`**

[Parámetros (CSV)](/images/android/Untitled%202c68bfd3e8498100baf9d17e8b7df5e0.csv)

**Ejemplo**

```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`**

[Parámetros (CSV)](/images/android/Untitled%202c68bfd3e84981b0bdecd417ba621e4e.csv)

**Ejemplo**

```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"
				}
	    }
	    ...
    ],
}
```
