From 0a7372035fdf4f24a3209f37227594a39886528d Mon Sep 17 00:00:00 2001
From: Matthieu Benoist <mbenoist@ausy-group.com>
Date: Thu, 4 Nov 2021 12:02:17 +0100
Subject: [PATCH] other licence initialization problem

---
 src/app/app.module.ts                         |   4 +-
 .../components/results/results.component.ts   | 117 +++++++++---------
 .../services/dataset-research.service.ts      |  92 +++++++-------
 3 files changed, 110 insertions(+), 103 deletions(-)

diff --git a/src/app/app.module.ts b/src/app/app.module.ts
index 163dc5c2..9cdf667c 100644
--- a/src/app/app.module.ts
+++ b/src/app/app.module.ts
@@ -17,7 +17,7 @@ import { notificationMessages } from '../i18n/traductions';
 // Function used by APP_INITIALIZER before the app start: init user info / statut (expect a promise)
 export function initUserService(authService: UserService, notificationService: NotificationService) {
   return (): Promise<any> => {
-    return new Promise((resolve, reject) => {
+    return new Promise<void>((resolve, reject) => {
       authService.initializeService().pipe(timeout(3000)).subscribe(
         () => {
           resolve();
@@ -37,7 +37,7 @@ export function initUserService(authService: UserService, notificationService: N
 
 export function initAppConfig(appConfigService: AppConfigService) {
   return (): Promise<any> => {
-    return new Promise((resolve, reject) => {
+    return new Promise<void>((resolve, reject) => {
       appConfigService.load();
       resolve();
     });
diff --git a/src/app/datasets/components/results/results.component.ts b/src/app/datasets/components/results/results.component.ts
index 119f4e1f..be701e47 100644
--- a/src/app/datasets/components/results/results.component.ts
+++ b/src/app/datasets/components/results/results.component.ts
@@ -52,8 +52,6 @@ export class ResultsComponent implements OnInit, OnDestroy {
 
   ngOnInit() {
 
-    console.log(`Titre vaut : ${ pageTitles.datasets }.`);
-    console.log(pageTitles);
     // Set the title and description for the research page
     this._meta.updateTag({ name: 'description', content: metaDescription.research });
 
@@ -94,64 +92,11 @@ export class ResultsComponent implements OnInit, OnDestroy {
 
   // If there are parameters, we extract them to set the ESoptions for a news search.
   private manageUrlParameters(params) {
-    this._datasetResearchService.resetActiveAggregations();
+    //this._datasetResearchService.resetActiveAggregations();
 
     if (params && Object.keys(params).length > 0) {
       this.hasParams = true;
-      // We need to make an initial request to get the aggregations and subaggregations
-      this._datasetResearchService.getResults().subscribe(() => {
-        // Create the ESOptions
-        const options = this._researchUrlService.getOptionsFromParameters(params);
-        this._datasetResearchService.elasticSearchOptions.setElasticsearchOptions(options);
-        // Force to recalculate the aggregate counts
-        this._datasetResearchService.shouldAggregateResultCount = true;
-        // Set the aggregations
-        const aggParameters = this._researchUrlService.aggParameters;
-
-        Object.keys(aggParameters).forEach((key) => {
-          const aggField = `metadata-fr.${key}`;
-          const oneAgg = aggParameters[key];
-
-          oneAgg.forEach((troncatedKey: string) => {
-            let newAggField = aggField;
-            let aggKey = '';
-
-            // Find out if it's an aggregation or subaggregation
-            const filters = this._datasetResearchService.elasticSearchOptions.filters;
-            let parentAgg = '';
-
-            filters.forEach((filter) => {
-              if (filter.field === aggField) {
-                // No need this rule. In this case we control the parameters, and we want a loose
-                // comparison to handle the filter with a 'Date' type (where the key aggregation is a number).
-                // tslint:disable-next-line: triple-equals
-                const aggregation = filter.aggregations.find(el => el.troncatedKey == troncatedKey);
-                if (aggregation) {
-                  aggKey = aggregation.key;
-                }
-              }
-              if (filter.subField === aggField) {
-                // We need to find the parent aggregation
-                filter.aggregations.forEach((aggregation) => {
-                  if (aggregation.subAggregations.length > 0) {
-                    const index = aggregation.subAggregations.findIndex(el => el.troncatedKey === troncatedKey);
-
-                    const subAggregation = aggregation.subAggregations[index];
-
-                    if (subAggregation) {
-                      aggKey = subAggregation.key;
-                      parentAgg = subAggregation.parentAggregation.key;
-                      newAggField = subAggregation.parentAggregation.field;
-                    }
-                  }
-                });
-              }
-            });
-            this._datasetResearchService.updateAggregation(newAggField, aggKey, true, parentAgg, false);
-          });
-        });
-        this._datasetResearchService.triggerSearchChange();
-      });
+      this.urlSearch(params);
     }
     else {
       //reset filters recorded when there are not get parameters
@@ -160,6 +105,64 @@ export class ResultsComponent implements OnInit, OnDestroy {
     }
   }
 
+  urlSearch(params) {
+    this._datasetResearchService.resetActiveAggregations();
+    this._datasetResearchService.getResults().subscribe(() => {
+
+      // Create the ESOptions
+      const options = this._researchUrlService.getOptionsFromParameters(params);
+      this._datasetResearchService.elasticSearchOptions.setElasticsearchOptions(options);
+      // Force to recalculate the aggregate counts
+      this._datasetResearchService.shouldAggregateResultCount = true;
+      // Set the aggregations
+      const aggParameters = this._researchUrlService.aggParameters;
+
+      Object.keys(aggParameters).forEach((key) => {
+        const aggField = `metadata-fr.${key}`;
+        const oneAgg = aggParameters[key];
+
+        oneAgg.forEach((troncatedKey: string) => {
+          let newAggField = aggField;
+          let aggKey = '';
+
+          // Find out if it's an aggregation or subaggregation
+          const filters = this._datasetResearchService.elasticSearchOptions.filters;
+          let parentAgg = '';
+
+          filters.forEach((filter) => {
+            if (filter.field === aggField) {
+              // No need this rule. In this case we control the parameters, and we want a loose
+              // comparison to handle the filter with a 'Date' type (where the key aggregation is a number).
+              // tslint:disable-next-line: triple-equals
+              const aggregation = filter.aggregations.find(el => el.troncatedKey == troncatedKey);
+              if (aggregation) {
+                aggKey = aggregation.key;
+              }
+            }
+            if (filter.subField === aggField) {
+              // We need to find the parent aggregation
+              filter.aggregations.forEach((aggregation) => {
+                if (aggregation.subAggregations.length > 0) {
+                  const index = aggregation.subAggregations.findIndex(el => el.troncatedKey === troncatedKey);
+
+                  const subAggregation = aggregation.subAggregations[index];
+
+                  if (subAggregation) {
+                    aggKey = subAggregation.key;
+                    parentAgg = subAggregation.parentAggregation.key;
+                    newAggField = subAggregation.parentAggregation.field;
+                  }
+                }
+              });
+            }
+          });
+          this._datasetResearchService.updateAggregation(newAggField, aggKey, true, parentAgg, false);
+        });
+      });
+      this._datasetResearchService.triggerSearchChange();
+    });
+  }
+
   ngOnDestroy() {
     this.searchChangeSub.unsubscribe();
     // Reset the url parameters
diff --git a/src/app/datasets/services/dataset-research.service.ts b/src/app/datasets/services/dataset-research.service.ts
index 1308666b..fff595b2 100644
--- a/src/app/datasets/services/dataset-research.service.ts
+++ b/src/app/datasets/services/dataset-research.service.ts
@@ -41,6 +41,7 @@ export class DatasetResearchService {
     this._resultsCount = [];
   }
 
+
   /**
    *  Get results from elasticsearch (can be Datasets or Articles).
    *  Options: filter by query string and pagination
@@ -49,43 +50,6 @@ export class DatasetResearchService {
     this._pendingRequests += 1;
     return this._elasticsearchService.getAllEntities(this._elasticsearchOptions).pipe(
       map((e) => {
-        // Set results count
-        if (this._elasticsearchOptions.shouldAggregateResultCount) {
-          this._resultsCount = [];
-          const countScopes = e.aggregations['count_by_scope'].buckets;
-          let countDatasets = 0;
-          countScopes.forEach((bucket) => {
-            if (scopesResearch.datasets.elasticType.includes(bucket.key)) {
-              countDatasets += bucket.count.value;
-            } else {
-              this._resultsCount.push({
-                scopeKey: bucket.key,
-                count: bucket.count.value,
-              });
-            }
-          });
-
-          // Datasets scope (datasets + non geographic datasets + series)
-          this._resultsCount.push({
-            scopeKey: scopesResearch.datasets.key,
-            count: countDatasets,
-          });
-
-          // All scope
-          const countAll = this._resultsCount.reduce((acc, obj) => {
-            const count = obj.scopeKey !== (scopesResearch.page.key&&scopesResearch.post.key) ? acc + obj.count : 0;
-            return count;
-            // tslint:disable-next-line:align
-          }, 0);
-          this._resultsCount.push({
-            scopeKey: scopesResearch.all.key,
-            count: countAll,
-          });
-        }
-
-        // Matomo tracking
-        this.angulartics2Piwik.eventTrack('trackSiteSearch', { keyword: this.searchString });
-
         if (this._elasticsearchOptions.shouldAggregateFilters) {
           // Get the aggregations that will be used to display the filters
           let aggregations = (e.hits.hits) ? e.aggregations : [];
@@ -161,13 +125,6 @@ export class DatasetResearchService {
             }
           });
         }
-        this._elasticsearchOptions.shouldAggregateFilters = true;
-        this._elasticsearchOptions.shouldAggregateResultCount = false;
-        this._elasticsearchOptions.fromAutocompletion = false;
-        // Notify that data have been reloaded
-        this._datasetsReloadedSubject.next();
-
-        this._pendingRequests -= 1;
 
         const results: any = [];
 
@@ -217,6 +174,50 @@ export class DatasetResearchService {
 
         });
 
+
+        // Set results count
+          this._resultsCount = [];
+          const countScopes = e.aggregations['count_by_scope'].buckets;
+          let countDatasets = 0;
+          countScopes.forEach((bucket) => {
+            if (scopesResearch.datasets.elasticType.includes(bucket.key)) {
+              countDatasets += bucket.count.value;
+            } else {
+              this._resultsCount.push({
+                scopeKey: bucket.key,
+                count: bucket.count.value,
+              });
+            }
+          });
+
+          // Datasets scope (datasets + non geographic datasets + series)
+          this._resultsCount.push({
+            scopeKey: scopesResearch.datasets.key,
+            count: countDatasets,
+          });
+
+          // All scope
+          const countAll = this._resultsCount.reduce((acc, obj) => {
+            const count = obj.scopeKey !== (scopesResearch.page.key&&scopesResearch.post.key) ? acc + obj.count : 0;
+            return count;
+            // tslint:disable-next-line:align
+          }, 0);
+          this._resultsCount.push({
+            scopeKey: scopesResearch.all.key,
+            count: countAll,
+          });
+
+        // Matomo tracking
+        this.angulartics2Piwik.eventTrack('trackSiteSearch', { keyword: this.searchString });
+
+        this._elasticsearchOptions.shouldAggregateFilters = true;
+        this._elasticsearchOptions.shouldAggregateResultCount = false;
+        this._elasticsearchOptions.fromAutocompletion = false;
+        // Notify that data have been reloaded
+        this._datasetsReloadedSubject.next();
+
+        this._pendingRequests -= 1;
+
         return results;
       }),
       catchError(
@@ -257,6 +258,9 @@ export class DatasetResearchService {
         }
       }
     }
+    if (!hasAlreadyOtherLicenses) {
+      this._searchChangeSubject.next();
+    }
     return aggregations;
   }
 
-- 
GitLab