Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(analytics): track events #557

Merged
merged 4 commits into from
Jan 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/auth/src/lib/auth-form/auth-form.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ export class AuthFormComponent implements OnInit {
}

private getName() {
if (this.auth.decodeToken()) {
const tokenDecoded = this.auth.decodeToken();
const tokenDecoded = this.auth.decodeToken();
if (tokenDecoded) {
this.user = {
name: tokenDecoded.user.firstName || tokenDecoded.user.sourceId
};
Expand Down
4 changes: 2 additions & 2 deletions packages/auth/src/lib/shared/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,9 @@ export class AuthService {
return this.http.get<User>(url);
}

getProfils() {
getProfils(): Observable<{ profils: string[] }> {
const url = this.config.getConfig('auth.url');
return this.http.get(`${url}/profils`);
return this.http.get<{ profils: string[] }>(`${url}/profils`);
}

updateUser(user: User): Observable<User> {
Expand Down
9 changes: 4 additions & 5 deletions packages/auth/src/lib/shared/profils.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { ConfigService } from '@igo2/core';
Expand All @@ -21,14 +20,14 @@ export class ProfilsGuard implements CanActivate {
private router: Router
) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
canActivate(_route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authService.getProfils().pipe(
map((profils: string[]) => {
map((profils: { profils: string[] }) => {
const authConfig = this.config.getConfig('auth');

if (
profils &&
profils.some(v => authConfig.profilsGuard.indexOf(v) !== -1)
profils.profils &&
profils.profils.some(v => authConfig.profilsGuard.indexOf(v) !== -1)
) {
return true;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/auth/src/lib/shared/token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class TokenService {

constructor(private injector: Injector) {}

set(token) {
set(token: string) {
localStorage.setItem(this.tokenKey, token);
}

Expand Down
33 changes: 22 additions & 11 deletions packages/context/src/lib/context-manager/shared/context.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ export class ContextService {

getDetails(id: string): Observable<DetailedContext> {
const url = `${this.baseUrl}/contexts/${id}/details`;
return this.http
.get<DetailedContext>(url)
.pipe(catchError(res => {
return this.http.get<DetailedContext>(url).pipe(
catchError(res => {
return this.handleError(res, id);
}));
})
);
}

getDefault(): Observable<DetailedContext> {
Expand Down Expand Up @@ -190,10 +190,13 @@ export class ContextService {
typePermission: type
};

return this.http.post<ContextPermission[]>(url, JSON.stringify(association))
.pipe(catchError(res => {
return [this.handleError(res, undefined, true)];
}));
return this.http
.post<ContextPermission[]>(url, JSON.stringify(association))
.pipe(
catchError(res => {
return [this.handleError(res, undefined, true)];
})
);
}

deletePermissionAssociation(
Expand Down Expand Up @@ -235,7 +238,7 @@ export class ContextService {
!l.id || self.findIndex(l2 => l2.id === l.id) === index
)
.reverse();
resMerge.toolbar = res.toolbar || resBase.toolbar;
resMerge.toolbar = res.toolbar || resBase.toolbar;
resMerge.tools = (res.tools || [])
.concat(resBase.tools || [])
.filter(
Expand Down Expand Up @@ -474,7 +477,11 @@ export class ContextService {
return `${basePath}/${file}`;
}

private handleError(error: HttpErrorResponse, uri: string, permissionError?: boolean): Message[] {
private handleError(
error: HttpErrorResponse,
uri: string,
permissionError?: boolean
): Message[] {
const context = this.contexts$.value.ours.find(obj => obj.uri === uri);
const titleContext = context ? context.title : uri;
error.error.title = this.languageService.translate.instant(
Expand Down Expand Up @@ -550,7 +557,11 @@ export class ContextService {
let found;
for (const key of Object.keys(contexts)) {
const value = contexts[key];
found = value.find(c => ((context.id && c.id === context.id) || (context.uri && c.uri === context.uri)));
found = value.find(
c =>
(context.id && c.id === context.id) ||
(context.uri && c.uri === context.uri)
);
if (found) {
break;
}
Expand Down
55 changes: 49 additions & 6 deletions packages/core/src/lib/analytics/shared/analytics.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { AnalyticsOptions } from './analytics.interface';
export class AnalyticsService {
private options: AnalyticsOptions;

get paq() {
return ((window as any)._paq = (window as any)._paq || []);
}

constructor(private config: ConfigService) {
this.options = this.config.getConfig('analytics') || {};

Expand All @@ -27,13 +31,11 @@ export class AnalyticsService {
? this.options.url + 'matomo'
: this.options.url;

(window as any)._paq = (window as any)._paq || [];
const paq: any = (window as any)._paq;
paq.push(['trackPageView']);
paq.push(['enableLinkTracking']);
// this.paq.push(['trackPageView']);
// this.paq.push(['enableLinkTracking']);
(() => {
paq.push(['setTrackerUrl', url + '.php']);
paq.push(['setSiteId', this.options.id]);
this.paq.push(['setTrackerUrl', url + '.php']);
this.paq.push(['setSiteId', this.options.id]);
const g = document.createElement('script');
const s = document.getElementsByTagName('script')[0];
g.type = 'text/javascript';
Expand All @@ -43,4 +45,45 @@ export class AnalyticsService {
s.parentNode.insertBefore(g, s);
})();
}

public setUser(
user?: {
id: number;
sourceId?: string;
firstName?: string;
lastName?: string;
},
profils?: string[]
) {
if (this.options.provider === 'matomo') {
if (!user) {
this.paq.push(['resetUserId']);
this.paq.push(['deleteCustomVariable', 1, 'user']);
this.paq.push(['deleteCustomVariable', 2, 'name']);
this.paq.push(['deleteCustomVariable', 3, 'profils']);
} else {
this.paq.push(['setUserId', user.id]);

const name = `${user.firstName} ${user.lastName}`;
this.paq.push(['setCustomVariable', 1, 'user', user.sourceId, 'visit']);
this.paq.push(['setCustomVariable', 2, 'name', name, 'visit']);
this.paq.push(['setCustomVariable', 3, 'profils', profils, 'visit']);
}

this.paq.push(['trackPageView']);
this.paq.push(['enableLinkTracking']);
}
}

public trackSearch(term: string, nbResults: number) {
if (this.options.provider === 'matomo') {
this.paq.push(['trackSiteSearch', term, false, nbResults]);
}
}

public trackEvent(category: string, action: string, name: string) {
if (this.options.provider === 'matomo') {
this.paq.push(['trackEvent', category, action, name]);
}
}
}
5 changes: 3 additions & 2 deletions packages/geo/src/lib/catalog/shared/catalog.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { EntityState } from '@igo2/common';
import { MetadataLayerOptions } from './../../metadata/shared/metadata.interface';
import { TooltipType } from '../../layer';
import { TimeFilterOptions } from '../../filter';
import { QueryFormat, QueryHtmlTarget } from '../../query';
import { QueryFormat, QueryHtmlTarget } from '../../query';

import { CatalogItemType } from './catalog.enum';

Expand Down Expand Up @@ -34,7 +34,8 @@ export interface CatalogItem {
type: CatalogItemType;
}

export interface CatalogItemLayer<L = MetadataLayerOptions> extends CatalogItem {
export interface CatalogItemLayer<L = MetadataLayerOptions>
extends CatalogItem {
options: L;
}

Expand Down
17 changes: 12 additions & 5 deletions packages/geo/src/lib/filter/shared/spatial-filter.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,19 @@ export class SpatialFilterService {
'igo.geo.terrapi.' + name
);
} catch (e) {
item.name = name.substring(0,1).toUpperCase() + name.substring(1, name.length - 1);
item.name =
name.substring(0, 1).toUpperCase() +
name.substring(1, name.length - 1);
}

try {
item.group = this.languageService.translate.instant(
'igo.geo.spatialFilter.group.' + substr
);
} catch (e) {
item.group = substr.substring(0,1).toUpperCase() + substr.substring(1, name.length - 1);
item.group =
substr.substring(0, 1).toUpperCase() +
substr.substring(1, name.length - 1);
}

items.push(item);
Expand All @@ -117,11 +121,14 @@ export class SpatialFilterService {
const name = this.getKeyByValue(this.urlFilterList, type);
try {
item.name = this.languageService.translate.instant(
'igo.geo.terrapi.' + name);
'igo.geo.terrapi.' + name
);
} catch (e) {
item.name = name.substring(0,1).toUpperCase() + name.substring(1, name.length - 1);
item.name =
name.substring(0, 1).toUpperCase() +
name.substring(1, name.length - 1);
}
item.source = type
item.source = type;

items.push(item);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { Injectable } from '@angular/core';
import { skip } from 'rxjs/operators';

import { AnalyticsService } from '@igo2/core';
import { AuthService } from '@igo2/auth';

import { ContextState } from '../context/context.state';
import { SearchState } from '../search/search.state';
import { ToolState } from '../tool/tool.state';

/**
* Service that holds the state of the search module
*/
@Injectable({
providedIn: 'root'
})
export class AnalyticsListenerService {
/**
* Toolbox that holds main tools
*/

constructor(
private analyticsService: AnalyticsService,
private authService: AuthService,
private contextState: ContextState,
private searchState: SearchState,
private toolState: ToolState
) {}

listen() {
this.listenUser();
this.listenContext();
this.listenTool();
this.listenSearch();
}

listenUser() {
this.authService.authenticate$.subscribe(() => {
const tokenDecoded = this.authService.decodeToken() || {};
if (tokenDecoded.user) {
this.authService
.getProfils()
.subscribe(profils =>
this.analyticsService.setUser(tokenDecoded.user, profils.profils)
);
} else {
this.analyticsService.setUser();
}
});
}

listenContext() {
this.contextState.context$.subscribe(context => {
if (context) {
this.analyticsService.trackEvent('context', 'activateContext', context.id || context.uri);
}
});
}

listenTool() {
this.toolState.toolbox.activeTool$.pipe(skip(1)).subscribe(tool => {
if (tool) {
this.analyticsService.trackEvent('tool', 'activateTool', tool.name);
}
});
}

listenSearch() {
this.searchState.searchTerm$.pipe(skip(1)).subscribe((searchTerm: string) => {
if (searchTerm !== undefined && searchTerm !== null) {
this.analyticsService.trackSearch(searchTerm, this.searchState.store.count);
}
});
}
}
8 changes: 8 additions & 0 deletions packages/integration/src/lib/analytics/analytics.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { NgModule } from '@angular/core';

@NgModule({
imports: [],
declarations: [],
exports: []
})
export class IgoAppAnalyticsModule {}
2 changes: 2 additions & 0 deletions packages/integration/src/lib/analytics/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './analytics-listener.service';
export * from './analytics.module';
2 changes: 2 additions & 0 deletions packages/integration/src/lib/integration.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NgModule } from '@angular/core';

import { IgoAppAnalyticsModule } from './analytics/analytics.module';
import { IgoAppContextModule } from './context/context.module';
import { IgoAppCatalogModule } from './catalog/catalog.module';
import { IgoAppDirectionsModule } from './directions/directions.module';
Expand All @@ -16,6 +17,7 @@ import { IgoAppAboutModule } from './about/about.module';
imports: [],
declarations: [],
exports: [
IgoAppAnalyticsModule,
IgoAppContextModule,
IgoAppCatalogModule,
IgoAppDirectionsModule,
Expand Down
2 changes: 2 additions & 0 deletions packages/integration/src/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

export * from './lib/integration.module';
export * from './lib/about/about.module';
export * from './lib/analytics/analytics.module';
export * from './lib/context/context.module';
export * from './lib/catalog/catalog.module';

Expand All @@ -18,6 +19,7 @@ export * from './lib/search/search.module';
export * from './lib/tool/tool.module';

export * from './lib/about';
export * from './lib/analytics';
export * from './lib/context';

export * from './lib/catalog/catalog-browser-tool/catalog-browser-tool.component';
Expand Down