]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/catalog/catalog.service.ts
LP1806087 Angular catalog Ang7 & lint repairs
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / catalog / catalog.service.ts
1 import {Injectable, EventEmitter} from '@angular/core';
2 import {Observable} from 'rxjs';
3 import {mergeMap, map, tap} from 'rxjs/operators';
4 import {OrgService} from '@eg/core/org.service';
5 import {UnapiService} from '@eg/share/catalog/unapi.service';
6 import {IdlService, IdlObject} from '@eg/core/idl.service';
7 import {NetService} from '@eg/core/net.service';
8 import {PcrudService} from '@eg/core/pcrud.service';
9 import {CatalogSearchContext, CatalogSearchState} from './search-context';
10 import {BibRecordService, BibRecordSummary} from './bib-record.service';
11 import {BasketService} from './basket.service';
12 import {CATALOG_CCVM_FILTERS} from './search-context';
13
14 @Injectable()
15 export class CatalogService {
16
17     ccvmMap: {[ccvm: string]: IdlObject[]} = {};
18     cmfMap: {[cmf: string]: IdlObject} = {};
19     copyLocations: IdlObject[];
20
21     // Keep a reference to the most recently retrieved facet data,
22     // since facet data is consistent across a given search.
23     // No need to re-fetch with every page of search data.
24     lastFacetData: any;
25     lastFacetKey: string;
26
27     // Allow anyone to watch for completed searches.
28     onSearchComplete: EventEmitter<CatalogSearchContext>;
29
30     constructor(
31         private idl: IdlService,
32         private net: NetService,
33         private org: OrgService,
34         private unapi: UnapiService,
35         private pcrud: PcrudService,
36         private bibService: BibRecordService,
37         private basket: BasketService
38     ) {
39         this.onSearchComplete = new EventEmitter<CatalogSearchContext>();
40
41     }
42
43     search(ctx: CatalogSearchContext): Promise<void> {
44         ctx.searchState = CatalogSearchState.SEARCHING;
45
46         if (ctx.showBasket) {
47             return this.basketSearch(ctx);
48         } else if (ctx.marcSearch.isSearchable()) {
49             return this.marcSearch(ctx);
50         } else if (ctx.identSearch.isSearchable() &&
51             ctx.identSearch.queryType === 'item_barcode') {
52             return this.barcodeSearch(ctx);
53         } else {
54             return this.termSearch(ctx);
55         }
56     }
57
58     barcodeSearch(ctx: CatalogSearchContext): Promise<void> {
59         return this.net.request(
60             'open-ils.search',
61             'open-ils.search.multi_home.bib_ids.by_barcode',
62             ctx.identSearch.value
63         ).toPromise().then(ids => {
64             const result = {
65                 count: ids.length,
66                 ids: ids.map(id => [id])
67             };
68
69             this.applyResultData(ctx, result);
70             ctx.searchState = CatalogSearchState.COMPLETE;
71             this.onSearchComplete.emit(ctx);
72         });
73     }
74
75     // "Search" the basket by loading the IDs and treating
76     // them like a standard query search results set.
77     basketSearch(ctx: CatalogSearchContext): Promise<void> {
78
79         return this.basket.getRecordIds().then(ids => {
80
81             // Map our list of IDs into a search results object
82             // the search context can understand.
83             const result = {
84                 count: ids.length,
85                 ids: ids.map(id => [id])
86             };
87
88             this.applyResultData(ctx, result);
89             ctx.searchState = CatalogSearchState.COMPLETE;
90             this.onSearchComplete.emit(ctx);
91         });
92     }
93
94     marcSearch(ctx: CatalogSearchContext): Promise<void> {
95         let method = 'open-ils.search.biblio.marc';
96         if (ctx.isStaff) { method += '.staff'; }
97
98         const queryStruct = ctx.compileMarcSearchArgs();
99
100         return this.net.request('open-ils.search', method, queryStruct)
101         .toPromise().then(result => {
102             // Match the query search return format
103             result.ids = result.ids.map(id => [id]);
104
105             this.applyResultData(ctx, result);
106             ctx.searchState = CatalogSearchState.COMPLETE;
107             this.onSearchComplete.emit(ctx);
108         });
109     }
110
111     termSearch(ctx: CatalogSearchContext): Promise<void> {
112
113         let method = 'open-ils.search.biblio.multiclass.query';
114         let fullQuery;
115
116         if (ctx.identSearch.isSearchable()) {
117             fullQuery = ctx.compileIdentSearchQuery();
118
119         } else {
120             fullQuery = ctx.compileTermSearchQuery();
121
122             if (ctx.termSearch.groupByMetarecord
123                 && !ctx.termSearch.fromMetarecord) {
124                 method = 'open-ils.search.metabib.multiclass.query';
125             }
126
127             if (ctx.termSearch.hasBrowseEntry) {
128                 this.fetchBrowseEntry(ctx);
129             }
130         }
131
132         console.debug(`search query: ${fullQuery}`);
133
134         if (ctx.isStaff) {
135             method += '.staff';
136         }
137
138         return new Promise((resolve, reject) => {
139             this.net.request(
140                 'open-ils.search', method, {
141                     limit : ctx.pager.limit + 1,
142                     offset : ctx.pager.offset
143                 }, fullQuery, true
144             ).subscribe(result => {
145                 this.applyResultData(ctx, result);
146                 ctx.searchState = CatalogSearchState.COMPLETE;
147                 this.onSearchComplete.emit(ctx);
148                 resolve();
149             });
150         });
151
152     }
153
154     // When showing titles linked to a browse entry, fetch
155     // the entry data as well so the UI can display it.
156     fetchBrowseEntry(ctx: CatalogSearchContext) {
157         const ts = ctx.termSearch;
158
159         const parts = ts.hasBrowseEntry.split(',');
160         const mbeId = parts[0];
161         const cmfId = parts[1];
162
163         this.pcrud.retrieve('mbe', mbeId)
164         .subscribe(mbe => ctx.termSearch.browseEntry = mbe);
165     }
166
167     applyResultData(ctx: CatalogSearchContext, result: any): void {
168         ctx.result = result;
169         ctx.pager.resultCount = result.count;
170
171         // records[] tracks the current page of bib summaries.
172         result.records = [];
173
174         // If this is a new search, reset the result IDs collection.
175         if (this.lastFacetKey !== result.facet_key) {
176             ctx.resultIds = [];
177         }
178
179         result.ids.forEach((blob, idx) => ctx.addResultId(blob[0], idx));
180     }
181
182     // Appends records to the search result set as they arrive.
183     // Returns a void promise once all records have been retrieved
184     fetchBibSummaries(ctx: CatalogSearchContext): Promise<void> {
185
186         const depth = ctx.global ?
187             ctx.org.root().ou_type().depth() :
188             ctx.searchOrg.ou_type().depth();
189
190         const isMeta = ctx.termSearch.isMetarecordSearch();
191
192         let observable: Observable<BibRecordSummary>;
193
194         if (isMeta) {
195             observable = this.bibService.getMetabibSummary(
196                 ctx.currentResultIds(), ctx.searchOrg.id(), depth);
197         } else {
198             observable = this.bibService.getBibSummary(
199                 ctx.currentResultIds(), ctx.searchOrg.id(), depth);
200         }
201
202         return observable.pipe(map(summary => {
203             // Responses are not necessarily returned in request-ID order.
204             let idx;
205             if (isMeta) {
206                 idx = ctx.currentResultIds().indexOf(summary.metabibId);
207             } else {
208                 idx = ctx.currentResultIds().indexOf(summary.id);
209             }
210
211             if (ctx.result.records) {
212                 // May be reset when quickly navigating results.
213                 ctx.result.records[idx] = summary;
214             }
215         })).toPromise();
216     }
217
218     fetchFacets(ctx: CatalogSearchContext): Promise<void> {
219
220         if (!ctx.result) {
221             return Promise.reject('Cannot fetch facets without results');
222         }
223
224         if (!ctx.result.facet_key) {
225             return Promise.resolve();
226         }
227
228         if (this.lastFacetKey === ctx.result.facet_key) {
229             ctx.result.facetData = this.lastFacetData;
230             return Promise.resolve();
231         }
232
233         return new Promise((resolve, reject) => {
234             this.net.request('open-ils.search',
235                 'open-ils.search.facet_cache.retrieve',
236                 ctx.result.facet_key
237             ).subscribe(facets => {
238                 const facetData = {};
239                 Object.keys(facets).forEach(cmfId => {
240                     const facetHash = facets[cmfId];
241                     const cmf = this.cmfMap[cmfId];
242
243                     const cmfData = [];
244                     Object.keys(facetHash).forEach(value => {
245                         const count = facetHash[value];
246                         cmfData.push({value : value, count : count});
247                     });
248
249                     if (!facetData[cmf.field_class()]) {
250                         facetData[cmf.field_class()] = {};
251                     }
252
253                     facetData[cmf.field_class()][cmf.name()] = {
254                         cmfLabel : cmf.label(),
255                         valueList : cmfData.sort((a, b) => {
256                             if (a.count > b.count) { return -1; }
257                             if (a.count < b.count) { return 1; }
258                             // secondary alpha sort on display value
259                             return a.value < b.value ? -1 : 1;
260                         })
261                     };
262                 });
263
264                 this.lastFacetKey = ctx.result.facet_key;
265                 this.lastFacetData = ctx.result.facetData = facetData;
266                 resolve();
267             });
268         });
269     }
270
271     fetchCcvms(): Promise<void> {
272
273         if (Object.keys(this.ccvmMap).length) {
274             return Promise.resolve();
275         }
276
277         return new Promise((resolve, reject) => {
278             this.pcrud.search('ccvm',
279                 {ctype : CATALOG_CCVM_FILTERS}, {},
280                 {atomic: true, anonymous: true}
281             ).subscribe(list => {
282                 this.compileCcvms(list);
283                 resolve();
284             });
285         });
286     }
287
288     compileCcvms(ccvms: IdlObject[]): void {
289         ccvms.forEach(ccvm => {
290             if (!this.ccvmMap[ccvm.ctype()]) {
291                 this.ccvmMap[ccvm.ctype()] = [];
292             }
293             this.ccvmMap[ccvm.ctype()].push(ccvm);
294         });
295
296         Object.keys(this.ccvmMap).forEach(cType => {
297             this.ccvmMap[cType] =
298                 this.ccvmMap[cType].sort((a, b) => {
299                     return a.value() < b.value() ? -1 : 1;
300                 });
301         });
302     }
303
304     iconFormatLabel(code: string): string {
305         if (this.ccvmMap) {
306             const ccvm = this.ccvmMap.icon_format.filter(
307                 format => format.code() === code)[0];
308             if (ccvm) {
309                 return ccvm.search_label();
310             }
311         }
312     }
313
314     fetchCmfs(): Promise<void> {
315         // At the moment, we only need facet CMFs.
316         if (Object.keys(this.cmfMap).length) {
317             return Promise.resolve();
318         }
319
320         return new Promise((resolve, reject) => {
321             this.pcrud.search('cmf',
322                 {facet_field : 't'}, {}, {atomic: true, anonymous: true}
323             ).subscribe(
324                 cmfs => {
325                     cmfs.forEach(c => this.cmfMap[c.id()] = c);
326                     resolve();
327                 }
328             );
329         });
330     }
331
332     fetchCopyLocations(contextOrg: number | IdlObject): Promise<any> {
333         const orgIds = this.org.fullPath(contextOrg, true);
334         this.copyLocations = [];
335
336         return this.pcrud.search('acpl',
337             {deleted: 'f', opac_visible: 't', owning_lib: orgIds},
338             {order_by: {acpl: 'name'}},
339             {anonymous: true}
340         ).pipe(tap(loc => this.copyLocations.push(loc))).toPromise();
341     }
342
343     browse(ctx: CatalogSearchContext): Observable<any> {
344         ctx.searchState = CatalogSearchState.SEARCHING;
345         const bs = ctx.browseSearch;
346
347         let method = 'open-ils.search.browse';
348         if (ctx.isStaff) {
349             method += '.staff';
350         }
351
352         return this.net.request(
353             'open-ils.search',
354             'open-ils.search.browse.staff', {
355                 browse_class: bs.fieldClass,
356                 term: bs.value,
357                 limit : ctx.pager.limit,
358                 pivot: bs.pivot,
359                 org_unit: ctx.searchOrg.id()
360             }
361         ).pipe(tap(result => {
362             ctx.searchState = CatalogSearchState.COMPLETE;
363         }));
364     }
365 }