# DACC

What is DACC ? A cozy blackbox where apps can send data in order to be anonymised and aggregate to provide usage stats.

## Infrastructure workflow

We have two environements, a dev one and a production. Both of them look like the following schema : 

![dacc](/img/architecture/dacc.png)

On the developpement env, the 'cozy env' refers to our 'Alpha' VM.

## Service

There is a service named `aggregatorUsageEvent`, running on a daily basis, sending pre-processed data to cozy. This service is responsible for parsing traced events store in database and send them to cozy. 

The service is configured to run every night at **01:00AM**.

## Usage events

This section explains how the application is tracking usage events. Here are the main step:

- All events are stored during the use of the application in the doctype **com.grandlyon.ecolyo.usageevents**
- A service is responsible of the aggregation of these events to create ANONYMIZED indicators. These indicators are then sent to a remote docType.


| Title | Tech name | target | context | startDate | result | trigger | Cozy Dacc Name | 
| --- | --- | --- | --- | --- | --- | --- | --- |
| Changement d'action dans un challenge | ActionChangeEvent | Id de l'action | Id du challenge en cours | --- | --- | Chaque appui sur le bouton `selectEcogesture` dans le `ActionCard` | navigation-action-daily |
| Validation de la fin d'une action | ActionEndEvent | Id de l'ecogeste | Id du challenge en cours | Date de début de l'action | --- | Lors de l'appui sur le bouton de fin d'action | event-duration |
| Connexion d'un utilisateur | ConnectionEvent | --- | Navigateur utilisé | --- | Si c'est la première connexion `firstConnection` est stocké | A chaque chargement de l'application | connection-count-daily |
| Connecteur Classique | KonnectorConnectEvent | Slug du connecteur | --- | --- | Success ou error | Le succès dans le cas ou on a la pop-up 'félicitation', le 'error' en cas d'erreur de quelque type que ce soit (catch) | konnector-event-daily |
| Connecteur Oauth (enedis, GRDF) | KonnectorConnectEvent | Slug du connecteur | --- | --- | Success ou error | Le succès dans le cas ou on a la pop-up 'félicitation', le 'error' dans le cas ou aucun accoun n'est créé | konnector-event-daily |
| Refresh manuel du connecteur | KonnectorRefreshEvent | Slug du connecteur | --- | --- | Success ou error. Le succès est set quand l'état du trigger est a 'done' | Lors de l'appuie sur le bouton 'mettre a jour' | konnector-event-daily |
| Navigation utilisateur dans l'application | NavigationEvent | Nom de la page ( voir 1. en dessous ) | --- | --- | --- | --- | navigation-count-daily |
| Comparaison de consomation | ConsumptionCompareEvent | timestep in lowercase | fluid type in lowercase | --- | --- | --- | navigation-action-daily |
| Changement de pas de temps | ConsumptionChangeTimeStepEvent | timestep in lowercase | fluid type | --- | --- | --- | navigation-action-daily |
| Lancement d'un challenge | ChallengeLaunchEvent | challenge id | --- | --- | --- | Appuie sur le bouton de lancement de challenge dans le cas on la pop-up 'pas de fluid' ne s'affiche pas | event-duration |
| Title | Tech name | target | context | startDate | result | trigger | Cozy Dacc Name | 
| Fin d'un challenge | ChallengeEndEvent | challenge id | --- | date de début du challenge | --- | Lors de la visualisation d'un challenge, si le resultat de celui-ci est a 'fini' on enregistre l'événement | event-duration |
| Début d'un duel | DuelLaunchEvent | duel id | challenge id | --- | --- | Appuie sur le bouton de lancement d'un duel | event-duration |
| Fin d'un duel | DuelEndEvent | duel id | --- | challenge start date | 'win' or 'loss' | Lors de la visualisation d'un duel, si le resultat de celui-ci est a 'fini' on enregistre l'événement | event-duration |
| Fin d'un quiz | QuizEndEvent | Quiz id | Challenge Id | Quiz start date | Resultat du quiz (de 0 a 5) | Lors de la pop-up de résultat | event-duration |
| --- | ExplorationEndEvent | --- | --- | --- | --- | --- | --- |
| --- | ActionChangeEvent | --- | --- | --- | --- | --- | --- |
| --- | ActionEndEvent | --- | --- | --- | --- | --- | --- |
| --- | ProfileSetEvent | --- | --- | --- | --- | --- | --- |
| --- | ReportFromEvent | --- | --- | --- | --- | --- | --- |



1. Nom de la page, différents cas existant

| Page | target | Trigger |
| --- | --- | --- |
| Consomation | 'electricity', 'gas', 'eau', 'multifluid' | Click sur un des fluids dans la bar navigation |
| FAQ | 'faq' | Click sur la card de consultation |
| CGU | 'legalNotice' | Click sur la card de Legal Notice |
| Autres | 'consumption' 'challenges' 'ecogestures' 'analysis' 'options' | Click dans la navbar |

## Indicators

!!! warning "note" 
    All indicators are only sent if a user validate first version of CGU, the one containing dacc validation
### Monthly Indicators

All monthly indicators call can be found after this comment on the code
```js
// Monthly events
```

| Indicator | Trigger | value |
| --- | --- | --- |
| consumption-variation-monthly | Tous les mois si l'utilisateur a été connecté au moins une fois dans le mois | La variation de consomation par type de fluide. La paramètres différents sont le type de profile ainsi ue le nombre de mois d'anciennetée |
| summary-subscription-monthly | Tous les mois si un utilisateur a souscrit a la newsletter ou c'est désabonné | 1 si l'utilsteur est inscrit sinon 0 |
| fluid-data-granularity-monthly | Tous les mois sans condition | 1 si l'utilisateur possède de la donnée a la demi heure sur le mois. Sinon 0 |
| connection-count-monthly | Tous les mois si il y a eu au moins une connexion | Le nombre de jour unique de connexion |
| profile-count-monthly | Tous les mois si le profil a été complété au moins une fois | Le nombre de fois ou le profile a été complété |


### Daily Indicators

The daily process get all events of previous day and process them in the following indicators

| Indicator | Trigger | value |
| --- | --- | --- |
| connection-count-daily | Tous les jours | Nombre de connexion. Celle-ci sont catégorisé par type (mobile ou desktop) |
| konnector-event-daily | Tous les jours | Nombre d'essai. Ils sont catégorisé par type de connecteur, refresh/success et le status (error ou success) |
| konnector-connected-daily | Tous les jours | La valeur est 1. Les valeurs sont catégorisées par type de fluide (electricity / electricity:water ...) |
| navigation-count-daily | Tous les jours | nombre de page visualisé par type de page |
| challenge-launch-daily | Tous les jours | Nombre de défis lancés lors d'un challenge  |
| session-duration | Tous les jours | Durée de la session en secondes |
| navigation-action-daily | Tous les jours | Nombre d'action sur une page donnée. Exemple sur la consomation on trace les changements de pas de temps sur chaque graph. |
| event-duration | Tous les jours | Durée entre deux événements: 
1ere session et premier challenge / début de challenge et fin de challenge / début d'exploration et fin d'exploration / début d'action et fin d'action / début de duel et fin de duel |
| quiz-stars | Tous les jours | Nombre d'étoiles obtenu a la fin d'un quiz |

## Information sending

### Format

All indicator are post to a remote doctype, which will allow the application to read a defined external API. This doctype is created by Cozy itself.
The structure to send is the following :

```
{
  createdBy: string
  measureName: string
  startDate: string
  value: number | null
  group1?: object
  group2?: object
  group3?: object
}
```

with:

- *createdBy*: contains "ecolyo" value.
- *startDate*: used to defined the start date of the indicator
- *value*: contains a value relevant to the defined indicator (example: number of page viewed on a day).
- *groups*: contains all attributes defining a indicator. Please refer to indicators definition (https://stats.cozycloud.cc/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjo0LCJxdWVyeSI6eyJzb3VyY2UtdGFibGUiOjh9LCJ0eXBlIjoicXVlcnkifSwiZGlzcGxheSI6InRhYmxlIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e319)
- *mesureName*: contains one of the following value 
  
| ENUM | value |
| --- | --- |
| CONNECTION_COUNT_DAILY  | connection-count-daily |
| KONNECTOR_EVENT_DAILY   | konnector-event-daily |
| KONNECTOR_CONNECTED_PER_DAY   | konnector-connected-daily |
| NAVIGATION_COUNT_DAILY   | navigation-count-daily |
| CHALLENGE_LAUNCH_EVENT_DAILY   | challenge-launch-daily |
| CONSUMPTION_VARIATION_MONTHLY   | consumption-variation-monthly |
| SESSION_DURATION   | session-duration |
| NAVIGATION_ACTION_DAILY   | navigation-action-daily |
| EVENT_DURATION   | event-duration |
| QUIZ_STARS    | quiz-stars |
| SUMMARY_SUBSCRIPTION_MONTHLY  | summary-subscription-monthly |
| FLUID_DATA_GRANULARITY    | fluid-data-granularity-monthly |
| CONNECTION_COUNT_MONTHLY    | connection-count-monthly |
| PROFILE_COUNT_MONTHLY    | profile-count-monthly |

### Environnements 

There is two remote doctypes pointing to two differents mode. `dacc-dev` is used on alpha.

```json
    "dacc": {
      "type": "cc.cozycloud.dacc",
      "verbs": ["ALL"]
    },
    "dacc-dev": {
      "type": "cc.cozycloud.dacc.dev",
      "verbs": ["ALL"]
    },
```

## How to local test ?

First you need to modify the service in order to be able to see data in local :


- Modify dacc URL in order to see data  (ligne 67)
```js
    await client
      .getStackClient()
      .fetchJSON(
        'POST',
        environementService.isProduction()
          ? 'http://localhost:8081'
          : '/remote/cc.cozycloud.dacc.dev',
        {
          data: JSON.stringify(indicator),
        }
      )
```
- Remove date protection if you want to test monthly indicators (ligne 1100)
```js
  if (
    profile
    // &&
    // DateTime.local()
    //   .setZone('utc', {
    //     keepLocalTime: true,
    //   })
    //   .startOf('day').day === profile.monthlyAnalysisDate.day
  ) {
```


Then you need to launch a script that will simulate dacc api's. This terminal will listen to incoming request

```sh
cd ./scripts
node server.js
```

Then you are finaly ready to test ! Just run the following :

```sh
yarn build-dev:browser; yarn run cozy-konnector-dev -m .\manifest.webapp .\build\services\fluidsPrices\ecolyo.js
```
You must see sent indicators in the previously open terminal 

```json
{
  data: '{"createdBy":"ecolyo","measureName":"connection-count-monthly","startDate":"2021-12-09","value":3}'
}
{
  data: '{"createdBy":"ecolyo","measureName":"connection-count-monthly","startDate":"2021-12-09","value":3}'
}
```

## How to add new indicator ? 

You have to reach cozy and discuss with them about new indicators. Thery will implement it for `dacc-dev` and `dacc` and you will be able to test it on alpha env. Remember you will need at least 5 data of each type to see it in metabase.

## Visualisation 

All the data aggregated in the dacc can be visualized with a *Metabase* website hosted by cozy (https://stats.cozycloud.cc/).