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';
15 export class CatalogService {
17 ccvmMap: {[ccvm: string]: IdlObject[]} = {};
18 cmfMap: {[cmf: string]: IdlObject} = {};
19 copyLocations: IdlObject[];
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.
27 // Allow anyone to watch for completed searches.
28 onSearchComplete: EventEmitter<CatalogSearchContext>;
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
39 this.onSearchComplete = new EventEmitter<CatalogSearchContext>();
43 search(ctx: CatalogSearchContext): Promise<void> {
44 ctx.searchState = CatalogSearchState.SEARCHING;
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);
55 ctx.identSearch.isSearchable() &&
56 ctx.identSearch.queryType === 'identifier|tcn') {
57 return this.tcnStaffSearch(ctx);
59 return this.termSearch(ctx);
63 barcodeSearch(ctx: CatalogSearchContext): Promise<void> {
64 return this.net.request(
66 'open-ils.search.multi_home.bib_ids.by_barcode',
68 ).toPromise().then(ids => {
69 // API returns an event for not-found barcodes
70 if (!Array.isArray(ids)) { ids = []; }
73 ids: ids.map(id => [id])
76 this.applyResultData(ctx, result);
77 ctx.searchState = CatalogSearchState.COMPLETE;
78 this.onSearchComplete.emit(ctx);
82 tcnStaffSearch(ctx: CatalogSearchContext): Promise<void> {
83 return this.net.request(
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);
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> {
100 return this.basket.getRecordIds().then(ids => {
103 ids.slice(ctx.pager.offset, ctx.pager.limit + ctx.pager.offset);
105 // Map our list of IDs into a search results object
106 // the search context can understand.
109 ids: pageIds.map(id => [id])
112 this.applyResultData(ctx, result);
113 ctx.searchState = CatalogSearchState.COMPLETE;
114 this.onSearchComplete.emit(ctx);
118 marcSearch(ctx: CatalogSearchContext): Promise<void> {
119 let method = 'open-ils.search.biblio.marc';
120 if (ctx.isStaff) { method += '.staff'; }
122 const queryStruct = ctx.compileMarcSearchArgs();
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]);
129 this.applyResultData(ctx, result);
130 ctx.searchState = CatalogSearchState.COMPLETE;
131 this.onSearchComplete.emit(ctx);
135 termSearch(ctx: CatalogSearchContext): Promise<void> {
137 let method = 'open-ils.search.biblio.multiclass.query';
140 if (ctx.identSearch.isSearchable()) {
141 fullQuery = ctx.compileIdentSearchQuery();
144 fullQuery = ctx.compileTermSearchQuery();
146 if (ctx.termSearch.groupByMetarecord
147 && !ctx.termSearch.fromMetarecord) {
148 method = 'open-ils.search.metabib.multiclass.query';
151 if (ctx.termSearch.hasBrowseEntry) {
152 this.fetchBrowseEntry(ctx);
156 console.debug(`search query: ${fullQuery}`);
162 return this.net.request(
163 'open-ils.search', method, {
164 limit : ctx.pager.limit + 1,
165 offset : ctx.pager.offset
168 .then(result => this.applyResultData(ctx, result))
169 .then(_ => this.fetchFieldHighlights(ctx))
171 ctx.searchState = CatalogSearchState.COMPLETE;
172 this.onSearchComplete.emit(ctx);
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;
181 const parts = ts.hasBrowseEntry.split(',');
182 const mbeId = parts[0];
183 const cmfId = parts[1];
185 this.pcrud.retrieve('mbe', mbeId)
186 .subscribe(mbe => ctx.termSearch.browseEntry = mbe);
189 applyResultData(ctx: CatalogSearchContext, result: any): void {
191 ctx.pager.resultCount = result.count;
193 // records[] tracks the current page of bib summaries.
196 // If this is a new search, reset the result IDs collection.
197 if (this.lastFacetKey !== result.facet_key) {
201 result.ids.forEach((blob, idx) => ctx.addResultId(blob[0], idx));
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> {
208 const depth = ctx.global ?
209 ctx.org.root().ou_type().depth() :
210 ctx.searchOrg.ou_type().depth();
212 const isMeta = ctx.termSearch.isMetarecordSearch();
214 let observable: Observable<BibRecordSummary>;
217 observable = this.bibService.getMetabibSummaries(
218 ctx.currentResultIds(), ctx.searchOrg.id(), ctx.isStaff);
220 observable = this.bibService.getBibSummaries(
221 ctx.currentResultIds(), ctx.searchOrg.id(), ctx.isStaff);
224 return observable.pipe(map(summary => {
225 // Responses are not necessarily returned in request-ID order.
228 idx = ctx.currentResultIds().indexOf(summary.metabibId);
230 idx = ctx.currentResultIds().indexOf(summary.id);
233 if (ctx.result.records) {
234 // May be reset when quickly navigating results.
235 ctx.result.records[idx] = summary;
238 if (ctx.highlightData[summary.id]) {
239 summary.displayHighlights = ctx.highlightData[summary.id];
244 fetchFieldHighlights(ctx: CatalogSearchContext): Promise<any> {
248 // Extract the highlight map. Not all searches have them.
249 if ((hlMap = ctx.result) &&
250 (hlMap = hlMap.global_summary) &&
251 (hlMap = hlMap.query_struct) &&
252 (hlMap = hlMap.additional_data) &&
253 (hlMap = hlMap.highlight_map) &&
254 (Object.keys(hlMap).length > 0)) {
255 } else { return Promise.resolve(); }
258 if (ctx.getHighlightsFor) {
259 ids = [ctx.getHighlightsFor];
261 // ctx.currentResultIds() returns bib IDs or metabib IDs
262 // depending on the search type. If we have metabib IDs, map
263 // them to bib IDs for highlighting.
264 ids = ctx.currentResultIds();
265 if (ctx.termSearch.groupByMetarecord) {
266 // The 4th slot in the result ID reports the master record
267 // for the metarecord in question. Sometimes it's null?
268 ids = ctx.result.ids.map(id => id[4]).filter(id => id !== null);
272 return this.net.requestWithParamList( // API is list-based
274 'open-ils.search.fetch.metabib.display_field.highlight',
276 ).pipe(map(fields => {
278 if (fields.length === 0) { return; }
280 // Each 'fields' collection is an array of display field
281 // values whose text is augmented with highlighting markup.
282 const highlights = ctx.highlightData[fields[0].source] = {};
284 fields.forEach(field => {
285 const dfMap = this.cmfMap[field.field].display_field_map();
286 if (!dfMap) { return; } // pretty sure this can't happen.
288 if (dfMap.multi() === 't') {
289 if (!highlights[dfMap.name()]) {
290 highlights[dfMap.name()] = [];
292 (highlights[dfMap.name()] as string[]).push(field.highlight);
294 highlights[dfMap.name()] = field.highlight;
301 fetchFacets(ctx: CatalogSearchContext): Promise<void> {
304 return Promise.reject('Cannot fetch facets without results');
307 if (!ctx.result.facet_key) {
308 return Promise.resolve();
311 if (this.lastFacetKey === ctx.result.facet_key) {
312 ctx.result.facetData = this.lastFacetData;
313 return Promise.resolve();
316 return new Promise((resolve, reject) => {
317 this.net.request('open-ils.search',
318 'open-ils.search.facet_cache.retrieve',
320 ).subscribe(facets => {
321 const facetData = {};
322 Object.keys(facets).forEach(cmfId => {
323 const facetHash = facets[cmfId];
324 const cmf = this.cmfMap[cmfId];
327 Object.keys(facetHash).forEach(value => {
328 const count = facetHash[value];
329 cmfData.push({value : value, count : count});
332 if (!facetData[cmf.field_class()]) {
333 facetData[cmf.field_class()] = {};
336 facetData[cmf.field_class()][cmf.name()] = {
337 cmfLabel : cmf.label(),
338 valueList : cmfData.sort((a, b) => {
339 if (a.count > b.count) { return -1; }
340 if (a.count < b.count) { return 1; }
341 // secondary alpha sort on display value
342 return a.value < b.value ? -1 : 1;
347 this.lastFacetKey = ctx.result.facet_key;
348 this.lastFacetData = ctx.result.facetData = facetData;
354 fetchCcvms(): Promise<void> {
356 if (Object.keys(this.ccvmMap).length) {
357 return Promise.resolve();
360 return new Promise((resolve, reject) => {
361 this.pcrud.search('ccvm',
362 {ctype : CATALOG_CCVM_FILTERS}, {},
363 {atomic: true, anonymous: true}
364 ).subscribe(list => {
365 this.compileCcvms(list);
371 compileCcvms(ccvms: IdlObject[]): void {
372 ccvms.forEach(ccvm => {
373 if (!this.ccvmMap[ccvm.ctype()]) {
374 this.ccvmMap[ccvm.ctype()] = [];
376 this.ccvmMap[ccvm.ctype()].push(ccvm);
379 Object.keys(this.ccvmMap).forEach(cType => {
380 this.ccvmMap[cType] =
381 this.ccvmMap[cType].sort((a, b) => {
382 return a.value() < b.value() ? -1 : 1;
387 iconFormatLabel(code: string): string {
389 const ccvm = this.ccvmMap.icon_format.filter(
390 format => format.code() === code)[0];
392 return ccvm.search_label();
397 fetchCmfs(): Promise<void> {
398 if (Object.keys(this.cmfMap).length) {
399 return Promise.resolve();
402 return new Promise((resolve, reject) => {
403 this.pcrud.search('cmf',
404 {'-or': [{facet_field : 't'}, {display_field: 't'}]},
405 {flesh: 1, flesh_fields: {cmf: ['display_field_map']}},
406 {atomic: true, anonymous: true}
409 cmfs.forEach(c => this.cmfMap[c.id()] = c);
416 fetchCopyLocations(contextOrg: number | IdlObject): Promise<any> {
417 const orgIds = this.org.fullPath(contextOrg, true);
418 this.copyLocations = [];
420 return this.pcrud.search('acpl',
421 {deleted: 'f', opac_visible: 't', owning_lib: orgIds},
422 {order_by: {acpl: 'name'}},
424 ).pipe(tap(loc => this.copyLocations.push(loc))).toPromise();
427 browse(ctx: CatalogSearchContext): Observable<any> {
428 ctx.searchState = CatalogSearchState.SEARCHING;
429 const bs = ctx.browseSearch;
431 let method = 'open-ils.search.browse';
436 return this.net.request(
438 'open-ils.search.browse.staff', {
439 browse_class: bs.fieldClass,
441 limit : ctx.pager.limit,
443 org_unit: ctx.searchOrg.id()
446 tap(result => ctx.searchState = CatalogSearchState.COMPLETE),
447 finalize(() => this.onSearchComplete.emit(ctx))
451 cnBrowse(ctx: CatalogSearchContext): Observable<any> {
452 ctx.searchState = CatalogSearchState.SEARCHING;
453 const cbs = ctx.cnBrowseSearch;
455 return this.net.request(
457 'open-ils.supercat.call_number.browse',
458 cbs.value, ctx.searchOrg.shortname(), cbs.limit, cbs.offset
459 ).pipe(tap(result => ctx.searchState = CatalogSearchState.COMPLETE));