-
-
Notifications
You must be signed in to change notification settings - Fork 204
/
search.service.ts
208 lines (182 loc) · 6.57 KB
/
search.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { Injectable, NgZone } from '@angular/core';
import * as _ from 'lodash-es';
import * as moment from 'moment';
import * as Search from '@medic/search';
import * as CalendarInterval from '@medic/calendar-interval';
import { DbService } from '@mm-services/db.service';
import { SessionService } from '@mm-services/session.service';
import { GetDataRecordsService } from '@mm-services/get-data-records.service';
import { PerformanceService } from '@mm-services/performance.service';
@Injectable({
providedIn: 'root'
})
export class SearchFactoryService {
constructor() {}
get(dbService) {
return Search(Promise, dbService.get());
}
}
@Injectable({
providedIn: 'root'
})
export class SearchService {
private searchFactory;
constructor(
private dbService:DbService,
private sessionService:SessionService,
private getDataRecordsService:GetDataRecordsService,
private searchFactoryService:SearchFactoryService,
private performanceService: PerformanceService,
private ngZone:NgZone,
) {
this.searchFactory = this.searchFactoryService.get(this.dbService);
}
private _currentQuery:any = {};
// Silently cancel repeated queries.
private debounce(type, filters, options) {
if (type === this._currentQuery.type &&
_.isEqual(filters, this._currentQuery.filters) &&
_.isEqual(options, this._currentQuery.options)) {
return true;
}
this._currentQuery.type = type;
this._currentQuery.filters = Object.assign({}, filters);
this._currentQuery.options = Object.assign({}, options);
return false;
}
private getLastVisitedDates(searchResults, searchResultsCache, settings) {
settings = settings || {};
const interval = CalendarInterval.getCurrent(settings.monthStartDate);
const visitStats = {};
searchResults.forEach((id) => {
visitStats[id] = { lastVisitedDate: -1, visitDates: [] };
});
const getVisitsInInterval = () => {
return this.dbService
.get()
.query('medic-client/visits_by_date', { start_key: interval.start, end_key: interval.end })
.then((result) => {
result.rows.forEach((row) => {
if (visitStats[row.value]) {
visitStats[row.value].visitDates.push(moment(row.key).startOf('day').valueOf());
}
});
});
};
const setLastVisitedDate = (rows) => {
rows.forEach((row) => {
if (visitStats[row.key]) {
visitStats[row.key].lastVisitedDate = _.isObject(row.value) ? row.value.max : row.value;
}
});
};
const getLastVisited = () => {
if (searchResultsCache) {
// when sorting by last visited date, we receive the data from Search library
return setLastVisitedDate(searchResultsCache);
}
let query;
if (this.sessionService.isOnlineOnly()) {
query = this.dbService.get().query(
'medic-client/contacts_by_last_visited',
{ reduce: true, group: true, keys: searchResults }
);
} else {
// querying with keys in PouchDB is very unoptimal
query = this.dbService.get().query(
'medic-client/contacts_by_last_visited',
{ reduce: true, group: true }
);
}
return query.then((result) => {
setLastVisitedDate(result.rows);
});
};
return getVisitsInInterval()
.then(getLastVisited)
.then(() => {
return Object.keys(visitStats)?.map((key) => {
return {
key: key,
value: {
lastVisitedDate: visitStats[key].lastVisitedDate,
visitCount: _.uniq(visitStats[key].visitDates).length,
visitCountGoal: settings.visitCountGoal
}
};
});
});
}
search(type, filters: Filter, options:any = {}, extensions:any = {}, docIds: any[] | undefined = undefined) {
return this.ngZone.runOutsideAngular(() => this._search(type, filters, options, extensions, docIds));
}
private _search(type, filters, options:any = {}, extensions:any = {}, docIds: any[] | undefined = undefined) {
console.debug('Doing Search', type, filters, options, extensions);
_.defaults(options, {
limit: 50,
skip: 0
});
if (!options.force && this.debounce(type, filters, options)) {
return Promise.resolve([]);
}
const trackPerformance = this.performanceService.track();
return this
.searchFactory(type, filters, options, extensions)
.then((searchResults) => {
const filterKeys = Object.keys(filters).filter(f => filters[f]).sort();
// Will end up with entries like:
// search:reports:search <-- text search of reports
// search:reports:date:search:valid:verified <-- maximum selected search of reports with text search
// search:contacts:search <-- text search of contacts
// search:contacts:types <-- default viewing of contact list
trackPerformance?.stop({ name: [ 'search', type, ...filterKeys ].join(':') });
if (docIds && docIds.length) {
docIds.forEach((docId) => {
if (searchResults.docIds.indexOf(docId) === -1) {
searchResults.docIds.push(docId);
}
});
}
const dataRecordsPromise = this.getDataRecordsService.get(searchResults.docIds, options);
if (!extensions.displayLastVisitedDate) {
return dataRecordsPromise;
}
const lastVisitedDatePromise = this.getLastVisitedDates(
searchResults.docIds,
searchResults.queryResultsCache,
extensions.visitCountSettings
);
return Promise
.all([
dataRecordsPromise,
lastVisitedDatePromise
])
.then(([dataRecords, lastVisitedDates]) => {
lastVisitedDates.forEach((dateResult) => {
const relevantDataRecord = dataRecords.find((dataRecord) => {
return dataRecord._id === dateResult.key;
});
if (relevantDataRecord) {
Object.assign(relevantDataRecord, dateResult.value);
relevantDataRecord.sortByLastVisitedDate = extensions.sortByLastVisitedDate;
}
});
return dataRecords;
});
})
.then((results) => {
this._currentQuery = {};
return results;
})
.catch((err) => {
this._currentQuery = {};
throw err;
});
}
}
export interface Filter {
types?: { selected: string };
search?: string;
parent?: string;
subjectIds?: string[];
}