d2e3044136eabae10afaf7f71277a95441316005
[evergreen-equinox.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 {map, tap, finalize} 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 if (
54             ctx.isStaff &&
55             ctx.identSearch.isSearchable() &&
56             ctx.identSearch.queryType === 'identifier|tcn') {
57             return this.tcnStaffSearch(ctx);
58         } else {
59             return this.termSearch(ctx);
60         }
61     }
62
63     barcodeSearch(ctx: CatalogSearchContext): Promise<void> {
64         return this.net.request(
65             'open-ils.search',
66             'open-ils.search.multi_home.bib_ids.by_barcode',
67             ctx.identSearch.value
68         ).toPromise().then(ids => {
69             // API returns an event for not-found barcodes
70             if (!Array.isArray(ids)) { ids = []; }
71             const result = {
72                 count: ids.length,
73                 ids: ids.map(id => [id])
74             };
75
76             this.applyResultData(ctx, result);
77             ctx.searchState = CatalogSearchState.COMPLETE;
78             this.onSearchComplete.emit(ctx);
79         });
80     }
81
82     tcnStaffSearch(ctx: CatalogSearchContext): Promise<void> {
83         return this.net.request(
84             'open-ils.search',
85             'open-ils.search.biblio.tcn',
86             ctx.identSearch.value, 1
87         ).toPromise().then(result => {
88             result.ids =  result.ids.map(id => [id]);
89             this.applyResultData(ctx, result);
90             ctx.searchState = CatalogSearchState.COMPLETE;
91             this.onSearchComplete.emit(ctx);
92         });
93     }
94
95
96     // "Search" the basket by loading the IDs and treating
97     // them like a standard query search results set.
98     basketSearch(ctx: CatalogSearchContext): Promise<void> {
99
100         return this.basket.getRecordIds().then(ids => {
101
102             const pageIds =
103                 ids.slice(ctx.pager.offset, ctx.pager.limit + ctx.pager.offset);
104
105             // Map our list of IDs into a search results object
106             // the search context can understand.
107             const result = {
108                 count: ids.length,
109                 ids: pageIds.map(id => [id])
110             };
111
112             this.applyResultData(ctx, result);
113             ctx.searchState = CatalogSearchState.COMPLETE;
114             this.onSearchComplete.emit(ctx);
115         });
116     }
117
118     marcSearch(ctx: CatalogSearchContext): Promise<void> {
119         let method = 'open-ils.search.biblio.marc';
120         if (ctx.isStaff) { method += '.staff'; }
121
122         const queryStruct = ctx.compileMarcSearchArgs();
123
124         return this.net.request('open-ils.search', method, queryStruct)
125         .toPromise().then(result => {
126             // Match the query search return format
127             result.ids = result.ids.map(id => [id]);
128
129             this.applyResultData(ctx, result);
130             ctx.searchState = CatalogSearchState.COMPLETE;
131             this.onSearchComplete.emit(ctx);
132         });
133     }
134
135     termSearch(ctx: CatalogSearchContext): Promise<void> {
136
137         let method = 'open-ils.search.biblio.multiclass.query';
138         let fullQuery;
139
140         if (ctx.identSearch.isSearchable()) {
141             fullQuery = ctx.compileIdentSearchQuery();
142
143         } else {
144             fullQuery = ctx.compileTermSearchQuery();
145
146             if (ctx.termSearch.groupByMetarecord
147                 && !ctx.termSearch.fromMetarecord) {
148                 method = 'open-ils.search.metabib.multiclass.query';
149             }
150
151             if (ctx.termSearch.hasBrowseEntry) {
152                 this.fetchBrowseEntry(ctx);
153             }
154         }
155
156         console.debug(`search query: ${fullQuery}`);
157
158         if (ctx.isStaff) {
159             method += '.staff';
160         }
161
162         return this.net.request(
163             'open-ils.search', method, {
164                 limit : ctx.pager.limit + 1,
165                 offset : ctx.pager.offset
166             }, fullQuery, true
167         ).toPromise()
168         .then(result => this.applyResultData(ctx, result))
169         .then(_ => this.fetchFieldHighlights(ctx))
170         .then(_ => {
171             ctx.searchState = CatalogSearchState.COMPLETE;
172             this.onSearchComplete.emit(ctx);
173         });
174     }
175
176     // When showing titles linked to a browse entry, fetch
177     // the entry data as well so the UI can display it.
178     fetchBrowseEntry(ctx: CatalogSearchContext) {
179         const ts = ctx.termSearch;
180
181         const parts = ts.hasBrowseEntry.split(',');
182         const mbeId = parts[0];
183         const cmfId = parts[1];
184
185         this.pcrud.retrieve('mbe', mbeId)
186         .subscribe(mbe => ctx.termSearch.browseEntry = mbe);
187     }
188
189     applyResultData(ctx: CatalogSearchContext, result: any): void {
190         ctx.result = result;
191         ctx.pager.resultCount = result.count;
192
193         // records[] tracks the current page of bib summaries.
194         result.records = [];
195
196         // If this is a new search, reset the result IDs collection.
197         if (this.lastFacetKey !== result.facet_key) {
198             ctx.resultIds = [];
199         }
200
201         result.ids.forEach((blob, idx) => ctx.addResultId(blob[0], idx));
202     }
203
204     // Appends records to the search result set as they arrive.
205     // Returns a void promise once all records have been retrieved
206     fetchBibSummaries(ctx: CatalogSearchContext): Promise<void> {
207
208         const org = ctx.global ? ctx.org.root() : ctx.searchOrg;
209         const depth = org.ou_type().depth();
210
211         const isMeta = ctx.termSearch.isMetarecordSearch();
212
213         let observable: Observable<BibRecordSummary>;
214
215         const options: any = {};
216         if (ctx.showResultExtras) {
217             options.flesh_copies = true;
218             options.copy_depth = depth;
219             options.copy_limit = 5;
220             options.pref_ou = ctx.prefOu;
221         }
222
223         if (isMeta) {
224             observable = this.bibService.getMetabibSummaries(
225                 ctx.currentResultIds(), ctx.searchOrg.id(), ctx.isStaff, options);
226         } else {
227             observable = this.bibService.getBibSummaries(
228                 ctx.currentResultIds(), ctx.searchOrg.id(), ctx.isStaff, options);
229         }
230
231         return observable.pipe(map(summary => {
232             // Responses are not necessarily returned in request-ID order.
233             let idx;
234             if (isMeta) {
235                 idx = ctx.currentResultIds().indexOf(summary.metabibId);
236             } else {
237                 idx = ctx.currentResultIds().indexOf(summary.id);
238             }
239
240             if (ctx.result.records) {
241                 // May be reset when quickly navigating results.
242                 ctx.result.records[idx] = summary;
243             }
244
245             if (ctx.highlightData[summary.id]) {
246                 summary.displayHighlights = ctx.highlightData[summary.id];
247             }
248         })).toPromise();
249     }
250
251     fetchFieldHighlights(ctx: CatalogSearchContext): Promise<any> {
252
253         let hlMap;
254
255         // Extract the highlight map.  Not all searches have them.
256         if ((hlMap = ctx.result)            &&
257             (hlMap = hlMap.global_summary)  &&
258             (hlMap = hlMap.query_struct)    &&
259             (hlMap = hlMap.additional_data) &&
260             (hlMap = hlMap.highlight_map)   &&
261             (Object.keys(hlMap).length > 0)) {
262         } else { return Promise.resolve(); }
263
264         let ids;
265         if (ctx.getHighlightsFor) {
266             ids = [ctx.getHighlightsFor];
267         } else {
268             // ctx.currentResultIds() returns bib IDs or metabib IDs
269             // depending on the search type.  If we have metabib IDs, map
270             // them to bib IDs for highlighting.
271             ids = ctx.currentResultIds();
272             if (ctx.termSearch.groupByMetarecord) {
273                 // The 4th slot in the result ID reports the master record
274                 // for the metarecord in question.  Sometimes it's null?
275                 ids = ctx.result.ids.map(id => id[4]).filter(id => id !== null);
276             }
277         }
278
279         return this.net.requestWithParamList( // API is list-based
280             'open-ils.search',
281             'open-ils.search.fetch.metabib.display_field.highlight',
282             [hlMap].concat(ids)
283         ).pipe(map(fields => {
284
285             if (fields.length === 0) { return; }
286
287             // Each 'fields' collection is an array of display field
288             // values whose text is augmented with highlighting markup.
289             const highlights = ctx.highlightData[fields[0].source] = {};
290
291             fields.forEach(field => {
292                 const dfMap = this.cmfMap[field.field].display_field_map();
293                 if (!dfMap) { return; } // pretty sure this can't happen.
294
295                 if (dfMap.multi() === 't') {
296                     if (!highlights[dfMap.name()]) {
297                         highlights[dfMap.name()] = [];
298                     }
299                     (highlights[dfMap.name()] as string[]).push(field.highlight);
300                 } else {
301                     highlights[dfMap.name()] = field.highlight;
302                 }
303             });
304
305         })).toPromise();
306     }
307
308     fetchFacets(ctx: CatalogSearchContext): Promise<void> {
309
310         if (!ctx.result) {
311             return Promise.reject('Cannot fetch facets without results');
312         }
313
314         if (!ctx.result.facet_key) {
315             return Promise.resolve();
316         }
317
318         if (this.lastFacetKey === ctx.result.facet_key) {
319             ctx.result.facetData = this.lastFacetData;
320             return Promise.resolve();
321         }
322
323         return new Promise((resolve, reject) => {
324             this.net.request('open-ils.search',
325                 'open-ils.search.facet_cache.retrieve',
326                 ctx.result.facet_key
327             ).subscribe(facets => {
328                 const facetData = {};
329                 Object.keys(facets).forEach(cmfId => {
330                     const facetHash = facets[cmfId];
331                     const cmf = this.cmfMap[cmfId];
332
333                     const cmfData = [];
334                     Object.keys(facetHash).forEach(value => {
335                         const count = facetHash[value];
336                         cmfData.push({value : value, count : count});
337                     });
338
339                     if (!facetData[cmf.field_class()]) {
340                         facetData[cmf.field_class()] = {};
341                     }
342
343                     facetData[cmf.field_class()][cmf.name()] = {
344                         cmfLabel : cmf.label(),
345                         valueList : cmfData.sort((a, b) => {
346                             if (a.count > b.count) { return -1; }
347                             if (a.count < b.count) { return 1; }
348                             // secondary alpha sort on display value
349                             return a.value < b.value ? -1 : 1;
350                         })
351                     };
352                 });
353
354                 this.lastFacetKey = ctx.result.facet_key;
355                 this.lastFacetData = ctx.result.facetData = facetData;
356                 resolve();
357             });
358         });
359     }
360
361     fetchCcvms(): Promise<void> {
362
363         if (Object.keys(this.ccvmMap).length) {
364             return Promise.resolve();
365         }
366
367         return new Promise((resolve, reject) => {
368             this.pcrud.search('ccvm',
369                 {ctype : CATALOG_CCVM_FILTERS}, {},
370                 {atomic: true, anonymous: true}
371             ).subscribe(list => {
372                 this.compileCcvms(list);
373                 resolve();
374             });
375         });
376     }
377
378     compileCcvms(ccvms: IdlObject[]): void {
379         ccvms.forEach(ccvm => {
380             if (!this.ccvmMap[ccvm.ctype()]) {
381                 this.ccvmMap[ccvm.ctype()] = [];
382             }
383             this.ccvmMap[ccvm.ctype()].push(ccvm);
384         });
385
386         Object.keys(this.ccvmMap).forEach(cType => {
387             this.ccvmMap[cType] =
388                 this.ccvmMap[cType].sort((a, b) => {
389                     return a.value() < b.value() ? -1 : 1;
390                 });
391         });
392     }
393
394     iconFormatLabel(code: string): string {
395         if (this.ccvmMap) {
396             const ccvm = this.ccvmMap.icon_format.filter(
397                 format => format.code() === code)[0];
398             if (ccvm) {
399                 return ccvm.search_label();
400             }
401         }
402     }
403
404     fetchCmfs(): Promise<void> {
405         if (Object.keys(this.cmfMap).length) {
406             return Promise.resolve();
407         }
408
409         return new Promise((resolve, reject) => {
410             this.pcrud.search('cmf',
411                 {'-or': [{facet_field : 't'}, {display_field: 't'}]},
412                 {flesh: 1, flesh_fields: {cmf: ['display_field_map']}},
413                 {atomic: true, anonymous: true}
414             ).subscribe(
415                 cmfs => {
416                     cmfs.forEach(c => this.cmfMap[c.id()] = c);
417                     resolve();
418                 }
419             );
420         });
421     }
422
423     fetchCopyLocations(contextOrg: number | IdlObject): Promise<any> {
424         const contextOrgId: any = this.org.get(contextOrg).id();
425
426         // we ordinarily want the shelving locations associated with
427         // all ancestors and descendants of the context OU, but
428         // if the context OU is the root, we intentionally want
429         // only the ones owned by the root OU
430         const orgIds: any[] = contextOrgId === this.org.root().id()
431             ? [contextOrgId]
432             : this.org.fullPath(contextOrg, true);
433
434         this.copyLocations = [];
435
436         return this.pcrud.search('acpl',
437             {deleted: 'f', opac_visible: 't', owning_lib: orgIds},
438             {order_by: {acpl: 'name'}},
439             {anonymous: true}
440         ).pipe(tap(loc => this.copyLocations.push(loc))).toPromise();
441     }
442
443     browse(ctx: CatalogSearchContext): Observable<any> {
444         ctx.searchState = CatalogSearchState.SEARCHING;
445         const bs = ctx.browseSearch;
446
447         let method = 'open-ils.search.browse';
448         if (ctx.isStaff) {
449             method += '.staff';
450         }
451
452         return this.net.request(
453             'open-ils.search',
454             'open-ils.search.browse.staff', {
455                 browse_class: bs.fieldClass,
456                 term: bs.value,
457                 limit : ctx.pager.limit,
458                 pivot: bs.pivot,
459                 org_unit: ctx.searchOrg.id()
460             }
461         ).pipe(
462             tap(result => ctx.searchState = CatalogSearchState.COMPLETE),
463             finalize(() => this.onSearchComplete.emit(ctx))
464         );
465     }
466
467     cnBrowse(ctx: CatalogSearchContext): Observable<any> {
468         ctx.searchState = CatalogSearchState.SEARCHING;
469         const cbs = ctx.cnBrowseSearch;
470
471         return this.net.request(
472             'open-ils.supercat',
473             'open-ils.supercat.call_number.browse',
474             cbs.value, ctx.searchOrg.shortname(), cbs.limit, cbs.offset
475         ).pipe(tap(result => ctx.searchState = CatalogSearchState.COMPLETE));
476     }
477 }