# Event Publishing and Application Insights in Asgardeo

Following the requirement to have the ability to analyze traffic patterns and user journeys ([see more](https://github.com/wso2-enterprise/asgardeo-product/issues/2348)) in Asgardeo, following two components are introduced.
- Event Publisher
- App Insights Publisher

This guide explains the basic details of these two components and a guideline to follow when adding a new event log.

## Table of Content

- [Event Publisher Class](#event-publisher-class)
    - Example Usage
    - Source Locations
- [App Insights Class](#app-insights-class)
    - Example Usage
    - Source Locations
    - Function Explanations
- [Publishing Events](#publishing-events)
- [Event Identifier Pattern](#event-identifier-pattern)
- [Related Issues](#related-issues)
- [Related PRs](#related-prs)
- [Improvement](#improvement)

## Event Publisher Class

This component is capable of publishing events. If you want to do any event logging for the on prem product, you can do it inside this class.

### Example Usage
This example is for the console. Same pattern can be applied to myaccount.

```typescript
import { EventPublisher } from "./features/core";

const eventPublisher = EventPublisher.getInstance();
eventPublisher.publish("sample-event");
```

or 

```typescript
eventPublisher.publish("sample-event", { 
    type: “value”
});
```

In case you have to perform some sort of computation before publishing insights (e.g. perform a set of if-else conditions or loop through an array), you should use the `compute` function.

```typescript
eventPublisher.compute(() => {
    /**
    * Computation - loop through an array
    */
    
    eventPublisher.publish("sample-event", { 
        type: “value”
    });
})
```

### Source Locations

- console: [view source](https://github.com/wso2/identity-apps/blob/master/apps/console/src/features/core/utils/event-publisher.ts)
- myaccount: [view source](https://github.com/wso2/identity-apps/blob/master/apps/myaccount/src/utils/event-publisher.ts)

## App Insights Class

This class is added with the capability to publish application insights logs to Azure application insights. Class should be added through asgardeo extensions and should install all the required dependencies. App Insights class is called through the on-prem event publisher class.

### Example Usage

This example is for the console. Same pattern can be applied to myaccount.

```typescript
import { analyticsConfig } from "../../../extensions/configs/analytics";

analyticsConfig.EventPublisherExtension.publish && 
    analyticsConfig.EventPublisherExtension.publish(eventId, customProperties);
```

### Source Locations

- console: [view source](https://github.com/wso2-enterprise/asgardeo-app-extensions/blob/master/app-extensions/console/src/extensions/utils/application-insights.ts)
- myaccount: [view source](https://github.com/wso2-enterprise/asgardeo-app-extensions/blob/master/app-extensions/myaccount/src/extensions/utils/application-insights.ts)

## Function Explanations

- `getInstance()`: To get an app insights object.
- `init()`: To initialize application insights.
- `compute(computation: () => void)`: To perform app insights related computations.
- `trackEvent(eventId: string, customProperties?: { [key: string]: string })`: To publish insights.

## Publishing Events

In order to publish events, first you should import the corresponding event publisher component and then should obtain an object.

```typescript
import { EventPublisher } from "./features/core";

const eventPublisher = EventPublisher.getInstance();

```

To publish click events, use the publish() function of the eventPublisher class.

### Parameters

- `eventId`: Event identifier (string).
- `customProperties`: Any custom properties to be published. Use `type` as the property key (optional object).

```typescript
eventPublisher.publish("sample-event", { 
    type: “value”
});
```

If you want to enable page tracking, there are two options to follow.

1. Use the `publish()` function of the eventPublisher class as above.

2. Uncomment [this line](https://github.com/wso2-enterprise/asgardeo-app-extensions/blob/master/app-extensions/console/src/extensions/utils/application-insights.ts#L109) and use the init() function of the eventPublisher class. Enabling this will make all the page visits to be published. Should consider the cost factor involved.


In app.tsx,
```typescript
eventPublisher.publish("page-visit-myaccount-landing-page");
```

or

```typescript
useEffect(() => {
	eventPublisher.init( );
}, [])
```

## Event Identifier Pattern

This section lists the common guidelines when creating event identifiers. Follow the below `eventid` pattern when publishing a new event.

&lt;page-or-tab-identifier&gt;-&lt;event-identifier&gt;

1. Use hyphens (-) to separate words. Don’t use spaces (kebabcase formatting).

    Eg: `application-register-new-application`

2. Use lowercase letters.

3. If the event can be in multiple apps (i.e. in both console and myaccount), append the app name as a prefix.

    Eg: console-getting-started

4. If there are any event specific data, pass them as custom properties. Use `type` as the property key.
You are required to format the custom property values into kebabcase formatting (i.e. need to replace spaces with hyphens and make it all lowercase).

    Eg:
    ```typescript
        eventPublisher.publish("application-sign-in-method-click-add", {
            type: "google-login"
        });
    ```

5. Example event identifier for a page visit:

    Eg: `page-visit-console-landing-page`

## Related Issues

- https://github.com/wso2-enterprise/asgardeo-product/issues/2348
- https://github.com/wso2-enterprise/asgardeo-product/issues/4562

## Related PRs
- https://github.com/wso2/identity-apps/pull/2202
- https://github.com/wso2/identity-apps/pull/2203
- https://github.com/wso2-enterprise/asgardeo-app-extensions/pull/826
- https://github.com/wso2-enterprise/asgardeo-app-extensions/pull/827

## Improvement

Two node modules should be installed only in asgardeo-app-extensions and not in on-prem setup. Those two node modules required to be added through a postinstall hook in package.json file (in both console and myaccount) and the installation script is being copied from extensions (will replace empty installation script in identity-apps). But the script failed to execute as the initialization life-cycle is being executed before copying the extension files.

Therefore currently as a workaround, installation script is added to asgardeo-app-extensions/script-extensions/pre-install.js and being executed through a <execution> tag in asgardeo-app-extensions/pom.xml.

Issue: https://github.com/wso2-enterprise/asgardeo-product/issues/5065
