]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Biblio.pm
no more caching of statuses in retrieve_all
[working/Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Search / Biblio.pm
1 package OpenILS::Application::Search::Biblio;
2 use base qw/OpenILS::Application/;
3 use strict; use warnings;
4
5
6 use OpenSRF::Utils::JSON;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Utils::ModsParser;
9 use OpenSRF::Utils::SettingsClient;
10 use OpenILS::Utils::CStoreEditor q/:funcs/;
11 use OpenSRF::Utils::Cache;
12 use Encode;
13
14 use OpenSRF::Utils::Logger qw/:logger/;
15
16
17 use OpenSRF::Utils::JSON;
18
19 use Time::HiRes qw(time);
20 use OpenSRF::EX qw(:try);
21 use Digest::MD5 qw(md5_hex);
22
23 use XML::LibXML;
24 use XML::LibXSLT;
25
26 use Data::Dumper;
27 $Data::Dumper::Indent = 0;
28
29 use OpenILS::Const qw/:const/;
30
31 use OpenILS::Application::AppUtils;
32 my $apputils = "OpenILS::Application::AppUtils";
33 my $U = $apputils;
34
35 my $pfx = "open-ils.search_";
36
37 my $cache;
38 my $cache_timeout;
39 my $superpage_size;
40 my $max_superpages;
41
42 sub initialize {
43         $cache = OpenSRF::Utils::Cache->new('global');
44         my $sclient = OpenSRF::Utils::SettingsClient->new();
45         $cache_timeout = $sclient->config_value(
46                         "apps", "open-ils.search", "app_settings", "cache_timeout" ) || 300;
47
48         $superpage_size = $sclient->config_value(
49                         "apps", "open-ils.search", "app_settings", "superpage_size" ) || 500;
50
51         $max_superpages = $sclient->config_value(
52                         "apps", "open-ils.search", "app_settings", "max_superpages" ) || 20;
53
54         $logger->info("Search cache timeout is $cache_timeout, ".
55         " superpage_size is $superpage_size, max_superpages is $max_superpages");
56 }
57
58
59
60 # ---------------------------------------------------------------------------
61 # takes a list of record id's and turns the docs into friendly 
62 # mods structures. Creates one MODS structure for each doc id.
63 # ---------------------------------------------------------------------------
64 sub _records_to_mods {
65         my @ids = @_;
66         
67         my @results;
68         my @marcxml_objs;
69
70         my $session = OpenSRF::AppSession->create("open-ils.cstore");
71         my $request = $session->request(
72                         "open-ils.cstore.direct.biblio.record_entry.search", { id => \@ids } );
73
74         while( my $resp = $request->recv ) {
75                 my $content = $resp->content;
76                 next if $content->id == OILS_PRECAT_RECORD;
77                 my $u = OpenILS::Utils::ModsParser->new();
78                 $u->start_mods_batch( $content->marc );
79                 my $mods = $u->finish_mods_batch();
80                 $mods->doc_id($content->id());
81                 $mods->tcn($content->tcn_value);
82                 push @results, $mods;
83         }
84
85         $session->disconnect();
86         return \@results;
87 }
88
89 __PACKAGE__->register_method(
90         method  => "record_id_to_mods",
91         api_name        => "open-ils.search.biblio.record.mods.retrieve",
92         argc            => 1, 
93         note            => "Provide ID, we provide the mods"
94 );
95
96 # converts a record into a mods object with copy counts attached
97 sub record_id_to_mods {
98
99         my( $self, $client, $org_id, $id ) = @_;
100
101         my $mods_list = _records_to_mods( $id );
102         my $mods_obj = $mods_list->[0];
103         my $cmethod = $self->method_lookup(
104                         "open-ils.search.biblio.record.copy_count");
105         my ($count) = $cmethod->run($org_id, $id);
106         $mods_obj->copy_count($count);
107
108         return $mods_obj;
109 }
110
111
112
113 __PACKAGE__->register_method(
114         method  => "record_id_to_mods_slim",
115     authoritative => 1,
116         api_name        => "open-ils.search.biblio.record.mods_slim.retrieve",
117         argc            => 1, 
118         note            => "Provide ID, we provide the mods"
119 );
120
121 # converts a record into a mods object with NO copy counts attached
122 sub record_id_to_mods_slim {
123         my( $self, $client, $id ) = @_;
124         return undef unless defined $id;
125
126         if(ref($id) and ref($id) == 'ARRAY') {
127                 return _records_to_mods( @$id );
128         }
129         my $mods_list = _records_to_mods( $id );
130         my $mods_obj = $mods_list->[0];
131         return OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND') unless $mods_obj;
132         return $mods_obj;
133 }
134
135
136 # Returns the number of copies attached to a record based on org location
137 __PACKAGE__->register_method(
138         method  => "record_id_to_copy_count",
139         api_name        => "open-ils.search.biblio.record.copy_count",
140 );
141
142 __PACKAGE__->register_method(
143         method  => "record_id_to_copy_count",
144     authoritative => 1,
145         api_name        => "open-ils.search.biblio.record.copy_count.staff",
146 );
147
148 __PACKAGE__->register_method(
149         method  => "record_id_to_copy_count",
150         api_name        => "open-ils.search.biblio.metarecord.copy_count",
151 );
152
153 __PACKAGE__->register_method(
154         method  => "record_id_to_copy_count",
155         api_name        => "open-ils.search.biblio.metarecord.copy_count.staff",
156 );
157 sub record_id_to_copy_count {
158         my( $self, $client, $org_id, $record_id, $format ) = @_;
159
160         return [] unless $record_id;
161         $format = undef if (!$format or $format eq 'all');
162
163         my $method = "open-ils.storage.biblio.record_entry.copy_count.atomic";
164         my $key = "record";
165
166         if($self->api_name =~ /metarecord/) {
167                 $method = "open-ils.storage.metabib.metarecord.copy_count.atomic";
168                 $key = "metarecord";
169         }
170
171         $method =~ s/atomic/staff\.atomic/og if($self->api_name =~ /staff/ );
172
173         my $count = $U->storagereq( $method, 
174                 org_unit => $org_id, $key => $record_id, format => $format );
175
176         return [ sort { $a->{depth} <=> $b->{depth} } @$count ];
177 }
178
179
180
181
182 __PACKAGE__->register_method(
183         method  => "biblio_search_tcn",
184         api_name        => "open-ils.search.biblio.tcn",
185         argc            => 3, 
186         note            => "Retrieve a record by TCN",
187 );
188
189 sub biblio_search_tcn {
190
191         my( $self, $client, $tcn, $include_deleted ) = @_;
192
193     $tcn =~ s/^\s+|\s+$//og;
194
195         my $e = new_editor();
196    my $search = {tcn_value => $tcn};
197    $search->{deleted} = 'f' unless $include_deleted;
198         my $recs = $e->search_biblio_record_entry( $search, {idlist =>1} );
199         
200         return { count => scalar(@$recs), ids => $recs };
201 }
202
203
204 # --------------------------------------------------------------------------------
205
206 __PACKAGE__->register_method(
207         method  => "biblio_barcode_to_copy",
208         api_name        => "open-ils.search.asset.copy.find_by_barcode",);
209 sub biblio_barcode_to_copy { 
210         my( $self, $client, $barcode ) = @_;
211         my( $copy, $evt ) = $U->fetch_copy_by_barcode($barcode);
212         return $evt if $evt;
213         return $copy;
214 }
215
216 __PACKAGE__->register_method(
217         method  => "biblio_id_to_copy",
218         api_name        => "open-ils.search.asset.copy.batch.retrieve",);
219 sub biblio_id_to_copy { 
220         my( $self, $client, $ids ) = @_;
221         $logger->info("Fetching copies @$ids");
222         return $U->cstorereq(
223                 "open-ils.cstore.direct.asset.copy.search.atomic", { id => $ids } );
224 }
225
226
227 __PACKAGE__->register_method(
228         method  => "copy_retrieve", 
229         api_name        => "open-ils.search.asset.copy.retrieve",);
230 sub copy_retrieve {
231         my( $self, $client, $cid ) = @_;
232         my( $copy, $evt ) = $U->fetch_copy($cid);
233         return $evt if $evt;
234         return $copy;
235 }
236
237 __PACKAGE__->register_method(
238         method  => "volume_retrieve", 
239         api_name        => "open-ils.search.asset.call_number.retrieve");
240 sub volume_retrieve {
241         my( $self, $client, $vid ) = @_;
242         my $e = new_editor();
243         my $vol = $e->retrieve_asset_call_number($vid) or return $e->event;
244         return $vol;
245 }
246
247 __PACKAGE__->register_method(
248         method  => "fleshed_copy_retrieve_batch",
249     authoritative => 1,
250         api_name        => "open-ils.search.asset.copy.fleshed.batch.retrieve");
251
252 sub fleshed_copy_retrieve_batch { 
253         my( $self, $client, $ids ) = @_;
254         $logger->info("Fetching fleshed copies @$ids");
255         return $U->cstorereq(
256                 "open-ils.cstore.direct.asset.copy.search.atomic",
257                 { id => $ids },
258                 { flesh => 1, 
259                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
260                 });
261 }
262
263
264 __PACKAGE__->register_method(
265         method  => "fleshed_copy_retrieve",
266         api_name        => "open-ils.search.asset.copy.fleshed.retrieve",);
267
268 sub fleshed_copy_retrieve { 
269         my( $self, $client, $id ) = @_;
270         my( $c, $e) = $U->fetch_fleshed_copy($id);
271         return $e if $e;
272         return $c;
273 }
274
275
276
277 __PACKAGE__->register_method(
278         method => 'fleshed_by_barcode',
279         api_name        => "open-ils.search.asset.copy.fleshed2.find_by_barcode",);
280 sub fleshed_by_barcode {
281         my( $self, $conn, $barcode ) = @_;
282         my $e = new_editor();
283         my $copyid = $e->search_asset_copy(
284                 {barcode => $barcode, deleted => 'f'}, {idlist=>1})->[0]
285                 or return $e->event;
286         return fleshed_copy_retrieve2( $self, $conn, $copyid);
287 }
288
289
290 __PACKAGE__->register_method(
291         method  => "fleshed_copy_retrieve2",
292         api_name        => "open-ils.search.asset.copy.fleshed2.retrieve",);
293
294 sub fleshed_copy_retrieve2 { 
295         my( $self, $client, $id ) = @_;
296         my $e = new_editor();
297         my $copy = $e->retrieve_asset_copy(
298                 [
299                         $id,
300                         { 
301                                 flesh                           => 2,
302                                 flesh_fields    => { 
303                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect / ],
304                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
305                                 }
306                         }
307                 ]
308         ) or return $e->event;
309
310         # For backwards compatibility
311         #$copy->stat_cat_entries($copy->stat_cat_entry_copy_maps);
312
313         if( $copy->status->id == OILS_COPY_STATUS_CHECKED_OUT ) {
314                 $copy->circulations(
315                         $e->search_action_circulation( 
316                                 [       
317                                         { target_copy => $copy->id },
318                                         {
319                                                 order_by => { circ => 'xact_start desc' },
320                                                 limit => 1
321                                         }
322                                 ]
323                         )
324                 );
325         }
326
327         return $copy;
328 }
329
330
331 __PACKAGE__->register_method(
332         method => 'flesh_copy_custom',
333         api_name => 'open-ils.search.asset.copy.fleshed.custom'
334 );
335
336 sub flesh_copy_custom {
337         my( $self, $conn, $copyid, $fields ) = @_;
338         my $e = new_editor();
339         my $copy = $e->retrieve_asset_copy(
340                 [
341                         $copyid,
342                         { 
343                                 flesh                           => 1,
344                                 flesh_fields    => { 
345                                         acp => $fields,
346                                 }
347                         }
348                 ]
349         ) or return $e->event;
350         return $copy;
351 }
352
353
354
355
356
357
358 __PACKAGE__->register_method(
359         method  => "biblio_barcode_to_title",
360         api_name        => "open-ils.search.biblio.find_by_barcode",
361 );
362
363 sub biblio_barcode_to_title {
364         my( $self, $client, $barcode ) = @_;
365
366         my $title = $apputils->simple_scalar_request(
367                 "open-ils.storage",
368                 "open-ils.storage.biblio.record_entry.retrieve_by_barcode", $barcode );
369
370         return { ids => [ $title->id ], count => 1 } if $title;
371         return { count => 0 };
372 }
373
374 __PACKAGE__->register_method(
375     method => 'title_id_by_item_barcode',
376     api_name => 'open-ils.search.bib_id.by_barcode'
377 );
378
379 sub title_id_by_item_barcode {
380     my( $self, $conn, $barcode ) = @_;
381     my $e = new_editor();
382     my $copies = $e->search_asset_copy(
383         [
384             { deleted => 'f', barcode => $barcode },
385             {
386                 flesh => 2,
387                 flesh_fields => {
388                     acp => [ 'call_number' ],
389                     acn => [ 'record' ]
390                 }
391             }
392         ]
393     );
394
395     return $e->event unless @$copies;
396     return $$copies[0]->call_number->record->id;
397 }
398
399
400 __PACKAGE__->register_method(
401         method  => "biblio_copy_to_mods",
402         api_name        => "open-ils.search.biblio.copy.mods.retrieve",
403 );
404
405 # takes a copy object and returns it fleshed mods object
406 sub biblio_copy_to_mods {
407         my( $self, $client, $copy ) = @_;
408
409         my $volume = $U->cstorereq( 
410                 "open-ils.cstore.direct.asset.call_number.retrieve",
411                 $copy->call_number() );
412
413         my $mods = _records_to_mods($volume->record());
414         $mods = shift @$mods;
415         $volume->copies([$copy]);
416         push @{$mods->call_numbers()}, $volume;
417
418         return $mods;
419 }
420
421
422 __PACKAGE__->register_method(
423     api_name => 'open-ils.search.biblio.multiclass.query',
424     method => 'multiclass_query',
425     signature => q#
426         @param arghash @see open-ils.search.biblio.multiclass
427         @param query Raw human-readable query string.  
428             Recognized search keys include: 
429                 keyword/kw - search keyword(s)
430                 author/au/name - search author(s)
431                 title/ti - search title
432                 subject/su - search subject
433                 series/se - search series
434                 lang - limit by language (specifiy multiple langs with lang:l1 lang:l2 ...)
435                 site - search at specified org unit, corresponds to actor.org_unit.shortname
436                 sort - sort type (title, author, pubdate)
437                 dir - sort direction (asc, desc)
438                 available - if set to anything other than "false" or "0", limits to available items
439
440                 keyword, title, author, subject, and series support additional search 
441                 subclasses, specified with a "|". For example, "title|proper:gone with the wind" 
442                 For more, see config.metabib_field
443
444         @param docache @see open-ils.search.biblio.multiclass
445     #
446 );
447 __PACKAGE__->register_method(
448     api_name => 'open-ils.search.biblio.multiclass.query.staff',
449     method => 'multiclass_query',
450     signature => '@see open-ils.search.biblio.multiclass.query');
451 __PACKAGE__->register_method(
452     api_name => 'open-ils.search.metabib.multiclass.query',
453     method => 'multiclass_query',
454     signature => '@see open-ils.search.biblio.multiclass.query');
455 __PACKAGE__->register_method(
456     api_name => 'open-ils.search.metabib.multiclass.query.staff',
457     method => 'multiclass_query',
458     signature => '@see open-ils.search.biblio.multiclass.query');
459
460 sub multiclass_query {
461     my($self, $conn, $arghash, $query, $docache) = @_;
462
463     $logger->debug("initial search query => $query");
464     my $orig_query = $query;
465
466     $query =~ s/\+/ /go;
467     $query =~ s/'/ /go;
468     $query =~ s/^\s+//go;
469
470     # convert convenience classes (e.g. kw for keyword) to the full class name
471     $query =~ s/kw(:|\|)/keyword$1/go;
472     $query =~ s/ti(:|\|)/title$1/go;
473     $query =~ s/au(:|\|)/author$1/go;
474     $query =~ s/su(:|\|)/subject$1/go;
475     $query =~ s/se(:|\|)/series$1/go;
476     $query =~ s/name(:|\|)/author$1/og;
477
478     $logger->debug("cleansed query string => $query");
479     my $search = $arghash->{searches} = {};
480
481     while ($query =~ s/((?:keyword(?:\|\w+)?|title(?:\|\w+)?|author(?:\|\w+)?|subject(?:\|\w+)?|series(?:\|\w+)?|site|dir|sort|lang|available):[^:]+)$//so) {
482         my($type, $value) = split(':', $1);
483         next unless $type and $value;
484
485         $value =~ s/^\s*//og;
486         $value =~ s/\s*$//og;
487         $type = 'sort_dir' if $type eq 'dir';
488
489         if($type eq 'site') {
490             # 'site' is the org shortname.  when using this, we also want 
491             # to search at the requested org's depth
492             my $e = new_editor();
493             if(my $org = $e->search_actor_org_unit({shortname => $value})->[0]) {
494                 $arghash->{org_unit} = $org->id if $org;
495                 $arghash->{depth} = $e->retrieve_actor_org_unit_type($org->ou_type)->depth;
496             } else {
497                 $logger->warn("'site:' query used on invalid org shortname: $value ... ignoring");
498             }
499
500         } elsif($type eq 'available') {
501             # limit to available
502             $arghash->{available} = 1 unless $value eq 'false' or $value eq '0';
503
504         } elsif($type eq 'lang') {
505             # collect languages into an array of languages
506             $arghash->{language} = [] unless $arghash->{language};
507             push(@{$arghash->{language}}, $value);
508
509         } elsif($type =~ /^sort/o) {
510             # sort and sort_dir modifiers
511             $arghash->{$type} = $value;
512
513         } else {
514             # append the search term to the term under construction
515             $search->{$type} =  {} unless $search->{$type};
516             $search->{$type}->{term} =  
517                 ($search->{$type}->{term}) ? $search->{$type}->{term} . " $value" : $value;
518         }
519     }
520
521     if($query) {
522         # This is the front part of the string before any special tokens were parsed. 
523         # Add this data to the default search class
524         my $type = $arghash->{default_class} || 'keyword';
525         $search->{$type} =  {} unless $search->{$type};
526         $search->{$type}->{term} =
527             ($search->{$type}->{term}) ? $search->{$type}->{term} . " $query" : $query;
528     }
529
530     # capture the original limit because the search method alters the limit internally
531     my $ol = $arghash->{limit};
532
533         my $sclient = OpenSRF::Utils::SettingsClient->new;
534
535     (my $method = $self->api_name) =~ s/\.query//o;
536
537     $method =~ s/multiclass/multiclass.staged/
538         if $sclient->config_value(apps => 'open-ils.search',
539             app_settings => 'use_staged_search') =~ /true/i;
540
541     $arghash->{preferred_language} = $U->get_org_locale($arghash->{org_unit})
542         unless $arghash->{preferred_language};
543
544         $method = $self->method_lookup($method);
545     my ($data) = $method->run($arghash, $docache);
546
547     $arghash->{limit} = $ol if $ol;
548     $data->{compiled_search} = $arghash;
549     $data->{query} = $orig_query;
550
551     $logger->info("compiled search is " . OpenSRF::Utils::JSON->perl2JSON($arghash));
552
553     return $data;
554 }
555
556 __PACKAGE__->register_method(
557         method          => 'cat_search_z_style_wrapper',
558         api_name        => 'open-ils.search.biblio.zstyle',
559         stream          => 1,
560         signature       => q/@see open-ils.search.biblio.multiclass/);
561
562 __PACKAGE__->register_method(
563         method          => 'cat_search_z_style_wrapper',
564         api_name        => 'open-ils.search.biblio.zstyle.staff',
565         stream          => 1,
566         signature       => q/@see open-ils.search.biblio.multiclass/);
567
568 sub cat_search_z_style_wrapper {
569         my $self = shift;
570         my $client = shift;
571         my $authtoken = shift;
572         my $args = shift;
573
574         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
575
576         my $ou = $cstore->request(
577                 'open-ils.cstore.direct.actor.org_unit.search',
578                 { parent_ou => undef }
579         )->gather(1);
580
581         my $result = { service => 'native-evergreen-catalog', records => [] };
582         my $searchhash = { limit => $$args{limit}, offset => $$args{offset}, org_unit => $ou->id };
583
584         $$searchhash{searches}{title}{term} = $$args{search}{title} if $$args{search}{title};
585         $$searchhash{searches}{author}{term} = $$args{search}{author} if $$args{search}{author};
586         $$searchhash{searches}{subject}{term} = $$args{search}{subject} if $$args{search}{subject};
587         $$searchhash{searches}{keyword}{term} = $$args{search}{keyword} if $$args{search}{keyword};
588
589         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{tcn} if $$args{search}{tcn};
590         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{isbn} if $$args{search}{isbn};
591         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{issn} if $$args{search}{issn};
592         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{publisher} if $$args{search}{publisher};
593         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{pubdate} if $$args{search}{pubdate};
594         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{item_type} if $$args{search}{item_type};
595
596         my $list = the_quest_for_knowledge( $self, $client, $searchhash );
597
598         if ($list->{count} > 0) {
599                 $result->{count} = $list->{count};
600
601                 my $records = $cstore->request(
602                         'open-ils.cstore.direct.biblio.record_entry.search.atomic',
603                         { id => [ map { ( $_->[0] ) } @{$list->{ids}} ] }
604                 )->gather(1);
605
606                 for my $rec ( @$records ) {
607                         
608                         my $u = OpenILS::Utils::ModsParser->new();
609                         $u->start_mods_batch( $rec->marc );
610                         my $mods = $u->finish_mods_batch();
611
612                         push @{ $result->{records} }, { mvr => $mods, marcxml => $rec->marc, bibid => $rec->id };
613
614                 }
615
616         }
617
618     $cstore->disconnect();
619         return $result;
620 }
621
622 # ----------------------------------------------------------------------------
623 # These are the main OPAC search methods
624 # ----------------------------------------------------------------------------
625
626 __PACKAGE__->register_method(
627         method          => 'the_quest_for_knowledge',
628         api_name                => 'open-ils.search.biblio.multiclass',
629         signature       => q/
630                 Performs a multi class biblio or metabib search
631                 @param searchhash A search object layed out like so:
632                         searches : { "$class" : "$value", ...}
633                         org_unit : The org id to focus the search at
634                         depth           : The org depth
635                         limit           : The search limit
636                         offset  : The search offset
637                         format  : The MARC format
638                         sort            : What field to sort the results on [ author | title | pubdate ]
639                         sort_dir        : What direction do we sort? [ asc | desc ]
640                 @return An object of the form 
641                         { "count" : $count, "ids" : [ [ $id, $relevancy, $total ], ...] }
642         /
643 );
644
645 __PACKAGE__->register_method(
646         method          => 'the_quest_for_knowledge',
647         api_name                => 'open-ils.search.biblio.multiclass.staff',
648         signature       => q/@see open-ils.search.biblio.multiclass/);
649 __PACKAGE__->register_method(
650         method          => 'the_quest_for_knowledge',
651         api_name                => 'open-ils.search.metabib.multiclass',
652         signature       => q/@see open-ils.search.biblio.multiclass/);
653 __PACKAGE__->register_method(
654         method          => 'the_quest_for_knowledge',
655         api_name                => 'open-ils.search.metabib.multiclass.staff',
656         signature       => q/@see open-ils.search.biblio.multiclass/);
657
658 sub the_quest_for_knowledge {
659         my( $self, $conn, $searchhash, $docache ) = @_;
660
661         return { count => 0 } unless $searchhash and
662                 ref $searchhash->{searches} eq 'HASH';
663
664         my $method = 'open-ils.storage.biblio.multiclass.search_fts';
665         my $ismeta = 0;
666         my @recs;
667
668         if($self->api_name =~ /metabib/) {
669                 $ismeta = 1;
670                 $method =~ s/biblio/metabib/o;
671         }
672
673
674         my $offset      = $searchhash->{offset} || 0;
675         my $limit       = $searchhash->{limit} || 10;
676         my $end         = $offset + $limit - 1;
677
678         # do some simple sanity checking
679         if(!$searchhash->{searches} or
680                 ( !grep { /^(?:title|author|subject|series|keyword)/ } keys %{$searchhash->{searches}} ) ) {
681                 return { count => 0 };
682         }
683
684
685         my $maxlimit = 5000;
686         $searchhash->{offset}   = 0;
687         $searchhash->{limit}            = $maxlimit;
688
689         return { count => 0 } if $offset > $maxlimit;
690
691         my @search;
692         push( @search, ($_ => $$searchhash{$_})) for (sort keys %$searchhash);
693         my $s = OpenSRF::Utils::JSON->perl2JSON(\@search);
694         my $ckey = $pfx . md5_hex($method . $s);
695
696         $logger->info("bib search for: $s");
697
698         $searchhash->{limit} -= $offset;
699
700
701     my $trim = 0;
702         my $result = ($docache) ? search_cache($ckey, $offset, $limit) : undef;
703
704         if(!$result) {
705
706                 $method .= ".staff" if($self->api_name =~ /staff/);
707                 $method .= ".atomic";
708         
709                 for (keys %$searchhash) { 
710                         delete $$searchhash{$_} 
711                                 unless defined $$searchhash{$_}; 
712                 }
713         
714                 $result = $U->storagereq( $method, %$searchhash );
715         $trim = 1;
716
717         } else { 
718                 $docache = 0; 
719         }
720
721         return {count => 0} unless ($result && $$result[0]);
722
723         @recs = @$result;
724
725         my $count = ($ismeta) ? $result->[0]->[3] : $result->[0]->[2];
726
727         if($docache) {
728                 # If we didn't get this data from the cache, put it into the cache
729                 # then return the correct offset of records
730                 $logger->debug("putting search cache $ckey\n");
731                 put_cache($ckey, $count, \@recs);
732         }
733
734     if($trim) {
735         # if we have the full set of data, trim out 
736         # the requested chunk based on limit and offset
737         my @t;
738         for ($offset..$end) {
739             last unless $recs[$_];
740             push(@t, $recs[$_]);
741         }
742         @recs = @t;
743     }
744
745         return { ids => \@recs, count => $count };
746 }
747
748
749 __PACKAGE__->register_method(
750         method          => 'staged_search',
751         api_name        => 'open-ils.search.biblio.multiclass.staged');
752 __PACKAGE__->register_method(
753         method          => 'staged_search',
754         api_name        => 'open-ils.search.biblio.multiclass.staged.staff',
755         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
756 __PACKAGE__->register_method(
757         method          => 'staged_search',
758         api_name        => 'open-ils.search.metabib.multiclass.staged',
759         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
760 __PACKAGE__->register_method(
761         method          => 'staged_search',
762         api_name        => 'open-ils.search.metabib.multiclass.staged.staff',
763         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
764
765 sub staged_search {
766         my($self, $conn, $search_hash, $docache) = @_;
767
768     my $method = ($self->api_name =~ /metabib/) ?
769         'open-ils.storage.metabib.multiclass.staged.search_fts':
770         'open-ils.storage.biblio.multiclass.staged.search_fts';
771
772     $method .= '.staff' if $self->api_name =~ /staff$/;
773     $method .= '.atomic';
774
775     my $search_duration;
776     my $user_offset = $search_hash->{offset} || 0; # user-specified offset
777     my $user_limit = $search_hash->{limit} || 10;
778     $user_offset = ($user_offset >= 0) ? $user_offset : 0;
779     $user_limit = ($user_limit >= 0) ? $user_limit : 10;
780
781
782     # we're grabbing results on a per-superpage basis, which means the 
783     # limit and offset should coincide with superpage boundaries
784     $search_hash->{offset} = 0;
785     $search_hash->{limit} = $superpage_size;
786
787     # force a well-known check_limit
788     $search_hash->{check_limit} = $superpage_size; 
789     # restrict total tested to superpage size * number of superpages
790     $search_hash->{core_limit} = $superpage_size * $max_superpages;
791
792     # Set the configured estimation strategy, defaults to 'inclusion'.
793         my $estimation_strategy = OpenSRF::Utils::SettingsClient
794         ->new
795         ->config_value(
796             apps => 'open-ils.search', app_settings => 'estimation_strategy'
797         ) || 'inclusion';
798         $search_hash->{estimation_strategy} = $estimation_strategy;
799
800     # pull any existing results from the cache
801     my $key = search_cache_key($method, $search_hash);
802     my $cache_data = $cache->get_cache($key) || {};
803
804     # keep retrieving results until we find enough to 
805     # fulfill the user-specified limit and offset
806     my $all_results = [];
807     my $page; # current superpage
808     my $est_hit_count = 0;
809     my $current_page_summary = {};
810     my $global_summary = {checked => 0, visible => 0, excluded => 0, deleted => 0, total => 0};
811     my $is_real_hit_count = 0;
812
813     for($page = 0; $page < $max_superpages; $page++) {
814
815         my $data = $cache_data->{$page};
816         my $results;
817         my $summary;
818
819         $logger->debug("staged search: analyzing superpage $page");
820
821         if($data) {
822             # this window of results is already cached
823             $logger->debug("staged search: found cached results");
824             $summary = $data->{summary};
825             $results = $data->{results};
826
827         } else {
828             # retrieve the window of results from the database
829             $logger->debug("staged search: fetching results from the database");
830             $search_hash->{skip_check} = $page * $superpage_size;
831             my $start = time;
832             $results = $U->storagereq($method, %$search_hash);
833             $search_duration = time - $start;
834             $logger->info("staged search: DB call took $search_duration seconds");
835             $summary = shift(@$results);
836
837             unless($summary) {
838                 $logger->info("search timed out: duration=$search_duration: params=".
839                     OpenSRF::Utils::JSON->perl2JSON($search_hash));
840                 return {count => 0};
841             }
842
843             my $hc = $summary->{estimated_hit_count} || $summary->{visible};
844             if($hc == 0) {
845                 $logger->info("search returned 0 results: duration=$search_duration: params=".
846                     OpenSRF::Utils::JSON->perl2JSON($search_hash));
847             }
848
849             # Create backwards-compatible result structures
850             if($self->api_name =~ /biblio/) {
851                 $results = [map {[$_->{id}]} @$results];
852             } else {
853                 $results = [map {[$_->{id}, $_->{rel}, $_->{record}]} @$results];
854             }
855
856             $results = [grep {defined $_->[0]} @$results];
857             cache_staged_search_page($key, $page, $summary, $results) if $docache;
858         }
859
860         $current_page_summary = $summary;
861
862         # add the new set of results to the set under construction
863         push(@$all_results, @$results);
864
865         my $current_count = scalar(@$all_results);
866
867         $est_hit_count = $summary->{estimated_hit_count} || $summary->{visible}
868             if $page == 0;
869
870         $logger->debug("staged search: located $current_count, with estimated hits=".
871             $summary->{estimated_hit_count}." : visible=".$summary->{visible}.", checked=".$summary->{checked});
872
873                 if (defined($summary->{estimated_hit_count})) {
874                         $global_summary->{checked} += $summary->{checked};
875                         $global_summary->{visible} += $summary->{visible};
876                         $global_summary->{excluded} += $summary->{excluded};
877                         $global_summary->{deleted} += $summary->{deleted};
878                         $global_summary->{total} = $summary->{total};
879                 }
880
881         # we've found all the possible hits
882         last if $current_count == $summary->{visible}
883             and not defined $summary->{estimated_hit_count};
884
885         # we've found enough results to satisfy the requested limit/offset
886         last if $current_count >= ($user_limit + $user_offset);
887
888         # we've scanned all possible hits
889         if($summary->{checked} < $superpage_size) {
890             $est_hit_count = scalar(@$all_results);
891             # we have all possible results in hand, so we know the final hit count
892             $is_real_hit_count = 1;
893             last;
894         }
895     }
896
897     my @results = grep {defined $_} @$all_results[$user_offset..($user_offset + $user_limit - 1)];
898
899         # refine the estimate if we have more than one superpage
900         if ($page > 0 and not $is_real_hit_count) {
901                 if ($global_summary->{checked} >= $global_summary->{total}) {
902                         $est_hit_count = $global_summary->{visible};
903                 } else {
904                         my $updated_hit_count = $U->storagereq(
905                                 'open-ils.storage.fts_paging_estimate',
906                                 $global_summary->{checked},
907                                 $global_summary->{visible},
908                                 $global_summary->{excluded},
909                                 $global_summary->{deleted},
910                                 $global_summary->{total}
911                         );
912                         $est_hit_count = $updated_hit_count->{$estimation_strategy};
913                 }
914         }
915
916     return {
917         count => $est_hit_count,
918         core_limit => $search_hash->{core_limit},
919         superpage_size => $search_hash->{check_limit},
920         superpage_summary => $current_page_summary,
921         ids => \@results
922     };
923 }
924
925 # creates a unique token to represent the query in the cache
926 sub search_cache_key {
927     my $method = shift;
928     my $search_hash = shift;
929         my @sorted;
930     for my $key (sort keys %$search_hash) {
931             push(@sorted, ($key => $$search_hash{$key})) 
932             unless $key eq 'limit' or 
933                 $key eq 'offset' or 
934                 $key eq 'skip_check';
935     }
936         my $s = OpenSRF::Utils::JSON->perl2JSON(\@sorted);
937         return $pfx . md5_hex($method . $s);
938 }
939
940 sub cache_staged_search_page {
941     # puts this set of results into the cache
942     my($key, $page, $summary, $results) = @_;
943     my $data = $cache->get_cache($key);
944     $data ||= {};
945     $data->{$page} = {
946         summary => $summary,
947         results => $results
948     };
949
950     $logger->info("staged search: cached with key=$key, superpage=$page, estimated=".
951         $summary->{estimated_hit_count}.", visible=".$summary->{visible});
952
953     $cache->put_cache($key, $data, $cache_timeout);
954 }
955
956 sub search_cache {
957
958         my $key         = shift;
959         my $offset      = shift;
960         my $limit       = shift;
961         my $start       = $offset;
962         my $end         = $offset + $limit - 1;
963
964         $logger->debug("searching cache for $key : $start..$end\n");
965
966         return undef unless $cache;
967         my $data = $cache->get_cache($key);
968
969         return undef unless $data;
970
971         my $count = $data->[0];
972         $data = $data->[1];
973
974         return undef unless $offset < $count;
975
976         my @result;
977         for( my $i = $offset; $i <= $end; $i++ ) {
978                 last unless my $d = $$data[$i];
979                 push( @result, $d );
980         }
981
982         $logger->debug("search_cache found ".scalar(@result)." items for count=$count, start=$start, end=$end");
983
984         return \@result;
985 }
986
987
988 sub put_cache {
989         my( $key, $count, $data ) = @_;
990         return undef unless $cache;
991         $logger->debug("search_cache putting ".
992                 scalar(@$data)." items at key $key with timeout $cache_timeout");
993         $cache->put_cache($key, [ $count, $data ], $cache_timeout);
994 }
995
996
997
998
999
1000
1001 __PACKAGE__->register_method(
1002         method  => "biblio_mrid_to_modsbatch_batch",
1003         api_name        => "open-ils.search.biblio.metarecord.mods_slim.batch.retrieve");
1004
1005 sub biblio_mrid_to_modsbatch_batch {
1006         my( $self, $client, $mrids) = @_;
1007         warn "Performing mrid_to_modsbatch_batch...";
1008         my @mods;
1009         my $method = $self->method_lookup("open-ils.search.biblio.metarecord.mods_slim.retrieve");
1010         for my $id (@$mrids) {
1011                 next unless defined $id;
1012                 my ($m) = $method->run($id);
1013                 push @mods, $m;
1014         }
1015         return \@mods;
1016 }
1017
1018
1019 __PACKAGE__->register_method(
1020         method  => "biblio_mrid_to_modsbatch",
1021         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve",
1022         notes           => <<"  NOTES");
1023         Returns the mvr associated with a given metarecod. If none exists, 
1024         it is created.
1025         NOTES
1026
1027 __PACKAGE__->register_method(
1028         method  => "biblio_mrid_to_modsbatch",
1029         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve.staff",
1030         notes           => <<"  NOTES");
1031         Returns the mvr associated with a given metarecod. If none exists, 
1032         it is created.
1033         NOTES
1034
1035 sub biblio_mrid_to_modsbatch {
1036         my( $self, $client, $mrid, $args) = @_;
1037
1038         warn "Grabbing mvr for $mrid\n";
1039
1040         my ($mr, $evt) = _grab_metarecord($mrid);
1041         return $evt unless $mr;
1042
1043         my $mvr = biblio_mrid_check_mvr($self, $client, $mr);
1044         $mvr = biblio_mrid_make_modsbatch( $self, $client, $mr ) unless $mvr;
1045
1046         return $mvr unless ref($args);  
1047
1048         # Here we find the lead record appropriate for the given filters 
1049         # and use that for the title and author of the metarecord
1050         my $format      = $$args{format};
1051         my $org         = $$args{org};
1052         my $depth       = $$args{depth};
1053
1054         return $mvr unless $format or $org or $depth;
1055
1056         my $method = "open-ils.storage.ordered.metabib.metarecord.records";
1057         $method = "$method.staff" if $self->api_name =~ /staff/o; 
1058
1059         my $rec = $U->storagereq($method, $format, $org, $depth, 1);
1060
1061         if( my $mods = $U->record_to_mvr($rec) ) {
1062
1063                 $mvr->title($mods->title);
1064                 $mvr->title($mods->author);
1065                 $logger->debug("mods_slim updating title and ".
1066                         "author in mvr with ".$mods->title." : ".$mods->author);
1067         }
1068
1069         return $mvr;
1070 }
1071
1072 # converts a metarecord to an mvr
1073 sub _mr_to_mvr {
1074         my $mr = shift;
1075         my $perl = OpenSRF::Utils::JSON->JSON2perl($mr->mods());
1076         return Fieldmapper::metabib::virtual_record->new($perl);
1077 }
1078
1079 # checks to see if a metarecord has mods, if so returns true;
1080
1081 __PACKAGE__->register_method(
1082         method  => "biblio_mrid_check_mvr",
1083         api_name        => "open-ils.search.biblio.metarecord.mods_slim.check",
1084         notes           => <<"  NOTES");
1085         Takes a metarecord ID or a metarecord object and returns true
1086         if the metarecord already has an mvr associated with it.
1087         NOTES
1088
1089 sub biblio_mrid_check_mvr {
1090         my( $self, $client, $mrid ) = @_;
1091         my $mr; 
1092
1093         my $evt;
1094         if(ref($mrid)) { $mr = $mrid; } 
1095         else { ($mr, $evt) = _grab_metarecord($mrid); }
1096         return $evt if $evt;
1097
1098         warn "Checking mvr for mr " . $mr->id . "\n";
1099
1100         return _mr_to_mvr($mr) if $mr->mods();
1101         return undef;
1102 }
1103
1104 sub _grab_metarecord {
1105         my $mrid = shift;
1106         #my $e = OpenILS::Utils::Editor->new;
1107         my $e = new_editor();
1108         my $mr = $e->retrieve_metabib_metarecord($mrid) or return ( undef, $e->event );
1109         return ($mr);
1110 }
1111
1112
1113 __PACKAGE__->register_method(
1114         method  => "biblio_mrid_make_modsbatch",
1115         api_name        => "open-ils.search.biblio.metarecord.mods_slim.create",
1116         notes           => <<"  NOTES");
1117         Takes either a metarecord ID or a metarecord object.
1118         Forces the creations of an mvr for the given metarecord.
1119         The created mvr is returned.
1120         NOTES
1121
1122 sub biblio_mrid_make_modsbatch {
1123         my( $self, $client, $mrid ) = @_;
1124
1125         #my $e = OpenILS::Utils::Editor->new;
1126         my $e = new_editor();
1127
1128         my $mr;
1129         if( ref($mrid) ) {
1130                 $mr = $mrid;
1131                 $mrid = $mr->id;
1132         } else {
1133                 $mr = $e->retrieve_metabib_metarecord($mrid) 
1134                         or return $e->event;
1135         }
1136
1137         my $masterid = $mr->master_record;
1138         $logger->info("creating new mods batch for metarecord=$mrid, master record=$masterid");
1139
1140         my $ids = $U->storagereq(
1141                 'open-ils.storage.ordered.metabib.metarecord.records.staff.atomic', $mrid);
1142         return undef unless @$ids;
1143
1144         my $master = $e->retrieve_biblio_record_entry($masterid)
1145                 or return $e->event;
1146
1147         # start the mods batch
1148         my $u = OpenILS::Utils::ModsParser->new();
1149         $u->start_mods_batch( $master->marc );
1150
1151         # grab all of the sub-records and shove them into the batch
1152         my @ids = grep { $_ ne $masterid } @$ids;
1153         #my $subrecs = (@ids) ? $e->batch_retrieve_biblio_record_entry(\@ids) : [];
1154
1155         my $subrecs = [];
1156         if(@$ids) {
1157                 for my $i (@$ids) {
1158                         my $r = $e->retrieve_biblio_record_entry($i);
1159                         push( @$subrecs, $r ) if $r;
1160                 }
1161         }
1162
1163         for(@$subrecs) {
1164                 $logger->debug("adding record ".$_->id." to mods batch for metarecord=$mrid");
1165                 $u->push_mods_batch( $_->marc ) if $_->marc;
1166         }
1167
1168
1169         # finish up and send to the client
1170         my $mods = $u->finish_mods_batch();
1171         $mods->doc_id($mrid);
1172         $client->respond_complete($mods);
1173
1174
1175         # now update the mods string in the db
1176         my $string = OpenSRF::Utils::JSON->perl2JSON($mods->decast);
1177         $mr->mods($string);
1178
1179         #$e = OpenILS::Utils::Editor->new(xact => 1);
1180         $e = new_editor(xact => 1);
1181         $e->update_metabib_metarecord($mr) 
1182                 or $logger->error("Error setting mods text on metarecord $mrid : " . Dumper($e->event));
1183         $e->finish;
1184
1185         return undef;
1186 }
1187
1188
1189
1190
1191 # converts a mr id into a list of record ids
1192
1193 __PACKAGE__->register_method(
1194         method  => "biblio_mrid_to_record_ids",
1195         api_name        => "open-ils.search.biblio.metarecord_to_records",
1196 );
1197
1198 __PACKAGE__->register_method(
1199         method  => "biblio_mrid_to_record_ids",
1200         api_name        => "open-ils.search.biblio.metarecord_to_records.staff",
1201 );
1202
1203 sub biblio_mrid_to_record_ids {
1204         my( $self, $client, $mrid, $args ) = @_;
1205
1206         my $format      = $$args{format};
1207         my $org         = $$args{org};
1208         my $depth       = $$args{depth};
1209
1210         my $method = "open-ils.storage.ordered.metabib.metarecord.records.atomic";
1211         $method =~ s/atomic/staff\.atomic/o if $self->api_name =~ /staff/o; 
1212         my $recs = $U->storagereq($method, $mrid, $format, $org, $depth);
1213
1214         return { count => scalar(@$recs), ids => $recs };
1215 }
1216
1217
1218 __PACKAGE__->register_method(
1219         method  => "biblio_record_to_marc_html",
1220         api_name        => "open-ils.search.biblio.record.html" );
1221
1222 __PACKAGE__->register_method(
1223         method  => "biblio_record_to_marc_html",
1224         api_name        => "open-ils.search.authority.to_html" );
1225
1226 my $parser = XML::LibXML->new();
1227 my $xslt = XML::LibXSLT->new();
1228 my $marc_sheet;
1229 my $slim_marc_sheet;
1230 my $settings_client = OpenSRF::Utils::SettingsClient->new();
1231
1232 sub biblio_record_to_marc_html {
1233         my($self, $client, $recordid, $slim, $marcxml) = @_;
1234
1235     my $sheet;
1236         my $dir = $settings_client->config_value("dirs", "xsl");
1237
1238     if($slim) {
1239         unless($slim_marc_sheet) {
1240                     my $xsl = $settings_client->config_value(
1241                             "apps", "open-ils.search", "app_settings", 'marc_html_xsl_slim');
1242             if($xsl) {
1243                         $xsl = $parser->parse_file("$dir/$xsl");
1244                         $slim_marc_sheet = $xslt->parse_stylesheet($xsl);
1245             }
1246         }
1247         $sheet = $slim_marc_sheet;
1248     }
1249
1250     unless($sheet) {
1251         unless($marc_sheet) {
1252             my $xsl_key = ($slim) ? 'marc_html_xsl_slim' : 'marc_html_xsl';
1253                     my $xsl = $settings_client->config_value(
1254                             "apps", "open-ils.search", "app_settings", 'marc_html_xsl');
1255                     $xsl = $parser->parse_file("$dir/$xsl");
1256                     $marc_sheet = $xslt->parse_stylesheet($xsl);
1257         }
1258         $sheet = $marc_sheet;
1259     }
1260
1261     my $record;
1262     unless($marcxml) {
1263         my $e = new_editor();
1264         if($self->api_name =~ /authority/) {
1265             $record = $e->retrieve_authority_record_entry($recordid)
1266                 or return $e->event;
1267         } else {
1268             $record = $e->retrieve_biblio_record_entry($recordid)
1269                 or return $e->event;
1270         }
1271         $marcxml = $record->marc;
1272     }
1273
1274         my $xmldoc = $parser->parse_string($marcxml);
1275         my $html = $sheet->transform($xmldoc);
1276         return $html->documentElement->toString();
1277 }
1278
1279
1280
1281 __PACKAGE__->register_method(
1282         method  => "retrieve_all_copy_statuses",
1283         api_name        => "open-ils.search.config.copy_status.retrieve.all" );
1284
1285 sub retrieve_all_copy_statuses {
1286         my( $self, $client ) = @_;
1287         return new_editor()->retrieve_all_config_copy_status();
1288 }
1289
1290
1291 __PACKAGE__->register_method(
1292         method  => "copy_counts_per_org",
1293         api_name        => "open-ils.search.biblio.copy_counts.retrieve");
1294
1295 __PACKAGE__->register_method(
1296         method  => "copy_counts_per_org",
1297         api_name        => "open-ils.search.biblio.copy_counts.retrieve.staff");
1298
1299 sub copy_counts_per_org {
1300         my( $self, $client, $record_id ) = @_;
1301
1302         warn "Retreiveing copy copy counts for record $record_id and method " . $self->api_name . "\n";
1303
1304         my $method = "open-ils.storage.biblio.record_entry.global_copy_count.atomic";
1305         if($self->api_name =~ /staff/) { $method =~ s/atomic/staff\.atomic/; }
1306
1307         my $counts = $apputils->simple_scalar_request(
1308                 "open-ils.storage", $method, $record_id );
1309
1310         $counts = [ sort {$a->[0] <=> $b->[0]} @$counts ];
1311         return $counts;
1312 }
1313
1314
1315 __PACKAGE__->register_method(
1316         method          => "copy_count_summary",
1317         api_name        => "open-ils.search.biblio.copy_counts.summary.retrieve",
1318         notes           => <<"  NOTES");
1319         returns an array of these:
1320                 [ org_id, callnumber_label, <status1_count>, <status2_cout>,...]
1321                 where statusx is a copy status name.  the statuses are sorted
1322                 by id.
1323         NOTES
1324
1325 sub copy_count_summary {
1326         my( $self, $client, $rid, $org, $depth ) = @_;
1327         $org ||= 1;
1328         $depth ||= 0;
1329     my $data = $U->storagereq(
1330                 'open-ils.storage.biblio.record_entry.status_copy_count.atomic', $rid, $org, $depth );
1331
1332     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1333 }
1334
1335 __PACKAGE__->register_method(
1336         method          => "copy_location_count_summary",
1337         api_name        => "open-ils.search.biblio.copy_location_counts.summary.retrieve",
1338         notes           => <<"  NOTES");
1339         returns an array of these:
1340                 [ org_id, callnumber_label, copy_location, <status1_count>, <status2_cout>,...]
1341                 where statusx is a copy status name.  the statuses are sorted
1342                 by id.
1343         NOTES
1344
1345 sub copy_location_count_summary {
1346         my( $self, $client, $rid, $org, $depth ) = @_;
1347         $org ||= 1;
1348         $depth ||= 0;
1349     my $data = $U->storagereq(
1350                 'open-ils.storage.biblio.record_entry.status_copy_location_count.atomic', $rid, $org, $depth );
1351
1352     return [ sort { $a->[1] cmp $b->[1] || $a->[2] cmp $b->[2] } @$data ];
1353 }
1354
1355 __PACKAGE__->register_method(
1356         method          => "copy_count_location_summary",
1357         api_name        => "open-ils.search.biblio.copy_counts.location.summary.retrieve",
1358         notes           => <<"  NOTES");
1359         returns an array of these:
1360                 [ org_id, callnumber_label, <status1_count>, <status2_cout>,...]
1361                 where statusx is a copy status name.  the statuses are sorted
1362                 by id.
1363         NOTES
1364
1365 sub copy_count_location_summary {
1366         my( $self, $client, $rid, $org, $depth ) = @_;
1367         $org ||= 1;
1368         $depth ||= 0;
1369     my $data = $U->storagereq(
1370         'open-ils.storage.biblio.record_entry.status_copy_location_count.atomic', $rid, $org, $depth );
1371     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1372 }
1373
1374
1375 __PACKAGE__->register_method(
1376         method          => "marc_search",
1377         api_name        => "open-ils.search.biblio.marc.staff");
1378
1379 __PACKAGE__->register_method(
1380         method          => "marc_search",
1381         api_name        => "open-ils.search.biblio.marc",
1382         notes           => <<"  NOTES");
1383                 Example:
1384                 open-ils.storage.biblio.full_rec.multi_search.atomic 
1385                 { "searches": [{"term":"harry","restrict": [{"tag":245,"subfield":"a"}]}], "org_unit": 1,
1386         "limit":5,"sort":"author","item_type":"g"}
1387         NOTES
1388
1389 sub marc_search {
1390         my( $self, $conn, $args, $limit, $offset ) = @_;
1391
1392         my $method = 'open-ils.storage.biblio.full_rec.multi_search';
1393         $method .= ".staff" if $self->api_name =~ /staff/;
1394         $method .= ".atomic";
1395
1396         $limit ||= 10;
1397         $offset ||= 0;
1398
1399         my @search;
1400         push( @search, ($_ => $$args{$_}) ) for (sort keys %$args);
1401         my $ckey = $pfx . md5_hex($method . OpenSRF::Utils::JSON->perl2JSON(\@search));
1402
1403         my $recs = search_cache($ckey, $offset, $limit);
1404
1405         if(!$recs) {
1406                 $recs = $U->storagereq($method, %$args) || [];
1407                 if( $recs ) {
1408                         put_cache($ckey, scalar(@$recs), $recs);
1409                         $recs = [ @$recs[$offset..($offset + ($limit - 1))] ];
1410                 } else {
1411                         $recs = [];
1412                 }
1413         }
1414
1415         my $count = 0;
1416         $count = $recs->[0]->[2] if $recs->[0] and $recs->[0]->[2];
1417         my @recs = map { $_->[0] } @$recs;
1418
1419         return { ids => \@recs, count => $count };
1420 }
1421
1422
1423 __PACKAGE__->register_method(
1424         method  => "biblio_search_isbn",
1425         api_name        => "open-ils.search.biblio.isbn",
1426 );
1427
1428 sub biblio_search_isbn { 
1429         my( $self, $client, $isbn ) = @_;
1430         $logger->debug("Searching ISBN $isbn");
1431         my $e = new_editor();
1432         my $recs = $U->storagereq(
1433                 'open-ils.storage.id_list.biblio.record_entry.search.isbn.atomic', $isbn );
1434         return { ids => $recs, count => scalar(@$recs) };
1435 }
1436
1437
1438 __PACKAGE__->register_method(
1439         method  => "biblio_search_issn",
1440         api_name        => "open-ils.search.biblio.issn",
1441 );
1442
1443 sub biblio_search_issn { 
1444         my( $self, $client, $issn ) = @_;
1445         $logger->debug("Searching ISSN $issn");
1446         my $e = new_editor();
1447         $issn =~ s/-/ /g;
1448         my $recs = $U->storagereq(
1449                 'open-ils.storage.id_list.biblio.record_entry.search.issn.atomic', $issn );
1450         return { ids => $recs, count => scalar(@$recs) };
1451 }
1452
1453
1454
1455
1456 __PACKAGE__->register_method(
1457         method  => "fetch_mods_by_copy",
1458         api_name        => "open-ils.search.biblio.mods_from_copy",
1459 );
1460
1461 sub fetch_mods_by_copy {
1462         my( $self, $client, $copyid ) = @_;
1463         my ($record, $evt) = $apputils->fetch_record_by_copy( $copyid );
1464         return $evt if $evt;
1465         return OpenILS::Event->new('ITEM_NOT_CATALOGED') unless $record->marc;
1466         return $apputils->record_to_mvr($record);
1467 }
1468
1469
1470
1471 # -------------------------------------------------------------------------------------
1472
1473 __PACKAGE__->register_method(
1474         method  => "cn_browse",
1475         api_name        => "open-ils.search.callnumber.browse.target",
1476         notes           => "Starts a callnumber browse"
1477         );
1478
1479 __PACKAGE__->register_method(
1480         method  => "cn_browse",
1481         api_name        => "open-ils.search.callnumber.browse.page_up",
1482         notes           => "Returns the previous page of callnumbers", 
1483         );
1484
1485 __PACKAGE__->register_method(
1486         method  => "cn_browse",
1487         api_name        => "open-ils.search.callnumber.browse.page_down",
1488         notes           => "Returns the next page of callnumbers", 
1489         );
1490
1491
1492 # RETURNS array of arrays like so: label, owning_lib, record, id
1493 sub cn_browse {
1494         my( $self, $client, @params ) = @_;
1495         my $method;
1496
1497         $method = 'open-ils.storage.asset.call_number.browse.target.atomic' 
1498                 if( $self->api_name =~ /target/ );
1499         $method = 'open-ils.storage.asset.call_number.browse.page_up.atomic'
1500                 if( $self->api_name =~ /page_up/ );
1501         $method = 'open-ils.storage.asset.call_number.browse.page_down.atomic'
1502                 if( $self->api_name =~ /page_down/ );
1503
1504         return $apputils->simplereq( 'open-ils.storage', $method, @params );
1505 }
1506 # -------------------------------------------------------------------------------------
1507
1508 __PACKAGE__->register_method(
1509         method => "fetch_cn",
1510     authoritative => 1,
1511         api_name => "open-ils.search.callnumber.retrieve",
1512         notes           => "retrieves a callnumber based on ID",
1513         );
1514
1515 sub fetch_cn {
1516         my( $self, $client, $id ) = @_;
1517         my( $cn, $evt ) = $apputils->fetch_callnumber( $id );
1518         return $evt if $evt;
1519         return $cn;
1520 }
1521
1522 __PACKAGE__->register_method (
1523         method          => "fetch_copy_by_cn",
1524         api_name                => 'open-ils.search.copies_by_call_number.retrieve',
1525         signature       => q/
1526                 Returns an array of copy id's by callnumber id
1527                 @param cnid The callnumber id
1528                 @return An array of copy ids
1529         /
1530 );
1531
1532 sub fetch_copy_by_cn {
1533         my( $self, $conn, $cnid ) = @_;
1534         return $U->cstorereq(
1535                 'open-ils.cstore.direct.asset.copy.id_list.atomic', 
1536                 { call_number => $cnid, deleted => 'f' } );
1537 }
1538
1539 __PACKAGE__->register_method (
1540         method          => 'fetch_cn_by_info',
1541         api_name                => 'open-ils.search.call_number.retrieve_by_info',
1542         signature       => q/
1543                 @param label The callnumber label
1544                 @param record The record the cn is attached to
1545                 @param org The owning library of the cn
1546                 @return The callnumber object
1547         /
1548 );
1549
1550
1551 sub fetch_cn_by_info {
1552         my( $self, $conn, $label, $record, $org ) = @_;
1553         return $U->cstorereq(
1554                 'open-ils.cstore.direct.asset.call_number.search',
1555                 { label => $label, record => $record, owning_lib => $org, deleted => 'f' });
1556 }
1557
1558
1559                 
1560
1561
1562 __PACKAGE__->register_method (
1563         method => 'bib_extras',
1564         api_name => 'open-ils.search.biblio.lit_form_map.retrieve.all');
1565 __PACKAGE__->register_method (
1566         method => 'bib_extras',
1567         api_name => 'open-ils.search.biblio.item_form_map.retrieve.all');
1568 __PACKAGE__->register_method (
1569         method => 'bib_extras',
1570         api_name => 'open-ils.search.biblio.item_type_map.retrieve.all');
1571 __PACKAGE__->register_method (
1572         method => 'bib_extras',
1573         api_name => 'open-ils.search.biblio.bib_level_map.retrieve.all');
1574 __PACKAGE__->register_method (
1575         method => 'bib_extras',
1576         api_name => 'open-ils.search.biblio.audience_map.retrieve.all');
1577
1578 sub bib_extras {
1579         my $self = shift;
1580
1581         my $e = new_editor();
1582
1583         return $e->retrieve_all_config_lit_form_map()
1584                 if( $self->api_name =~ /lit_form/ );
1585
1586         return $e->retrieve_all_config_item_form_map()
1587                 if( $self->api_name =~ /item_form_map/ );
1588
1589         return $e->retrieve_all_config_item_type_map()
1590                 if( $self->api_name =~ /item_type_map/ );
1591
1592         return $e->retrieve_all_config_bib_level_map()
1593                 if( $self->api_name =~ /bib_level_map/ );
1594
1595         return $e->retrieve_all_config_audience_map()
1596                 if( $self->api_name =~ /audience_map/ );
1597
1598         return [];
1599 }
1600
1601
1602
1603 __PACKAGE__->register_method(
1604         method  => 'fetch_slim_record',
1605         api_name        => 'open-ils.search.biblio.record_entry.slim.retrieve',
1606         signature=> q/
1607                 Returns a biblio.record_entry without the attached marcxml
1608         /
1609 );
1610
1611 sub fetch_slim_record {
1612         my( $self, $conn, $ids ) = @_;
1613
1614         #my $editor = OpenILS::Utils::Editor->new;
1615         my $editor = new_editor();
1616         my @res;
1617         for( @$ids ) {
1618                 return $editor->event unless
1619                         my $r = $editor->retrieve_biblio_record_entry($_);
1620                 $r->clear_marc;
1621                 push(@res, $r);
1622         }
1623         return \@res;
1624 }
1625
1626
1627
1628 __PACKAGE__->register_method(
1629         method => 'rec_to_mr_rec_descriptors',
1630         api_name        => 'open-ils.search.metabib.record_to_descriptors',
1631         signature       => q/
1632                 specialized method...
1633                 Given a biblio record id or a metarecord id, 
1634                 this returns a list of metabib.record_descriptor
1635                 objects that live within the same metarecord
1636                 @param args Object of args including:
1637         /
1638 );
1639
1640 sub rec_to_mr_rec_descriptors {
1641         my( $self, $conn, $args ) = @_;
1642
1643         my $rec = $$args{record};
1644         my $mrec        = $$args{metarecord};
1645         my $item_forms = $$args{item_forms};
1646         my $item_types  = $$args{item_types};
1647         my $item_lang   = $$args{item_lang};
1648
1649         my $e = new_editor();
1650         my $recs;
1651
1652         if( !$mrec ) {
1653                 my $map = $e->search_metabib_metarecord_source_map({source => $rec});
1654                 return $e->event unless @$map;
1655                 $mrec = $$map[0]->metarecord;
1656         }
1657
1658         $recs = $e->search_metabib_metarecord_source_map({metarecord => $mrec});
1659         return $e->event unless @$recs;
1660
1661         my @recs = map { $_->source } @$recs;
1662         my $search = { record => \@recs };
1663         $search->{item_form} = $item_forms if $item_forms and @$item_forms;
1664         $search->{item_type} = $item_types if $item_types and @$item_types;
1665         $search->{item_lang} = $item_lang if $item_lang;
1666
1667         my $desc = $e->search_metabib_record_descriptor($search);
1668
1669         return { metarecord => $mrec, descriptors => $desc };
1670 }
1671
1672
1673
1674
1675 __PACKAGE__->register_method(
1676         method => 'copies_created_on',  
1677 );
1678
1679
1680 sub copies_created_on {
1681         my( $self, $conn, $auth, $org, $date ) = @_;
1682         my $e = new_editor(authtoken=>$auth);
1683         return $e->event unless $e->checkauth;
1684 }
1685
1686
1687 __PACKAGE__->register_method(
1688         method => 'fetch_age_protect',
1689         api_name => 'open-ils.search.copy.age_protect.retrieve.all',
1690 );
1691
1692 sub fetch_age_protect {
1693         return new_editor()->retrieve_all_config_rule_age_hold_protect();
1694 }
1695
1696
1697 __PACKAGE__->register_method(
1698         method => 'copies_by_cn_label',
1699         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label',
1700 );
1701
1702 __PACKAGE__->register_method(
1703         method => 'copies_by_cn_label',
1704         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label.staff',
1705 );
1706
1707 sub copies_by_cn_label {
1708         my( $self, $conn, $record, $label, $circ_lib ) = @_;
1709         my $e = new_editor();
1710         my $cns = $e->search_asset_call_number({record => $record, label => $label, deleted => 'f'}, {idlist=>1});
1711         return [] unless @$cns;
1712
1713         # show all non-deleted copies in the staff client ...
1714         if ($self->api_name =~ /staff$/o) {
1715                 return $e->search_asset_copy({call_number => $cns, circ_lib => $circ_lib, deleted => 'f'}, {idlist=>1});
1716         }
1717
1718         # ... otherwise, grab the copies ...
1719         my $copies = $e->search_asset_copy(
1720                 [ {call_number => $cns, circ_lib => $circ_lib, deleted => 'f', opac_visible => 't'},
1721                   {flesh => 1, flesh_fields => { acp => [ qw/location status/] } }
1722                 ]
1723         );
1724
1725         # ... and test for location and status visibility
1726         return [ map { ($U->is_true($_->location->opac_visible) && $U->is_true($_->status->opac_visible)) ? ($_->id) : () } @$copies ];
1727 }
1728
1729
1730
1731 1;
1732
1733