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