]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Biblio.pm
enabled authoritative for several methods
[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 __PACKAGE__->register_method(
508     api_name => 'open-ils.search.biblio.multiclass.query',
509     method => 'multiclass_query',
510     signature => q#
511         @param arghash @see open-ils.search.biblio.multiclass
512         @param query Raw human-readable query string.  
513             Recognized search keys include: 
514                 keyword/kw - search keyword(s)
515                 author/au/name - search author(s)
516                 title/ti - search title
517                 subject/su - search subject
518                 series/se - search series
519                 lang - limit by language (specifiy multiple langs with lang:l1 lang:l2 ...)
520                 site - search at specified org unit, corresponds to actor.org_unit.shortname
521                 sort - sort type (title, author, pubdate)
522                 dir - sort direction (asc, desc)
523                 available - if set to anything other than "false" or "0", limits to available items
524
525                 keyword, title, author, subject, and series support additional search 
526                 subclasses, specified with a "|". For example, "title|proper:gone with the wind" 
527                 For more, see config.metabib_field
528
529         @param docache @see open-ils.search.biblio.multiclass
530     #
531 );
532 __PACKAGE__->register_method(
533     api_name => 'open-ils.search.biblio.multiclass.query.staff',
534     method => 'multiclass_query',
535     signature => '@see open-ils.search.biblio.multiclass.query');
536 __PACKAGE__->register_method(
537     api_name => 'open-ils.search.metabib.multiclass.query',
538     method => 'multiclass_query',
539     signature => '@see open-ils.search.biblio.multiclass.query');
540 __PACKAGE__->register_method(
541     api_name => 'open-ils.search.metabib.multiclass.query.staff',
542     method => 'multiclass_query',
543     signature => '@see open-ils.search.biblio.multiclass.query');
544
545 sub multiclass_query {
546     my($self, $conn, $arghash, $query, $docache) = @_;
547
548     $logger->debug("initial search query => $query");
549     my $orig_query = $query;
550
551     $query =~ s/\+/ /go;
552     $query =~ s/'/ /go;
553     $query =~ s/^\s+//go;
554
555     # convert convenience classes (e.g. kw for keyword) to the full class name
556     $query =~ s/kw(:|\|)/keyword$1/go;
557     $query =~ s/ti(:|\|)/title$1/go;
558     $query =~ s/au(:|\|)/author$1/go;
559     $query =~ s/su(:|\|)/subject$1/go;
560     $query =~ s/se(:|\|)/series$1/go;
561     $query =~ s/name(:|\|)/author$1/og;
562
563     $logger->debug("cleansed query string => $query");
564     my $search = $arghash->{searches} = {};
565
566     while ($query =~ s/((?:keyword(?:\|\w+)?|title(?:\|\w+)?|author(?:\|\w+)?|subject(?:\|\w+)?|series(?:\|\w+)?|site|dir|sort|lang|available):[^:]+)$//so) {
567         my($type, $value) = split(':', $1);
568         next unless $type and $value;
569
570         $value =~ s/^\s*//og;
571         $value =~ s/\s*$//og;
572         $type = 'sort_dir' if $type eq 'dir';
573
574         if($type eq 'site') {
575             # 'site' is the org shortname.  when using this, we also want 
576             # to search at the requested org's depth
577             my $e = new_editor();
578             if(my $org = $e->search_actor_org_unit({shortname => $value})->[0]) {
579                 $arghash->{org_unit} = $org->id if $org;
580                 $arghash->{depth} = $e->retrieve_actor_org_unit_type($org->ou_type)->depth;
581             } else {
582                 $logger->warn("'site:' query used on invalid org shortname: $value ... ignoring");
583             }
584
585         } elsif($type eq 'available') {
586             # limit to available
587             $arghash->{available} = 1 unless $value eq 'false' or $value eq '0';
588
589         } elsif($type eq 'lang') {
590             # collect languages into an array of languages
591             $arghash->{language} = [] unless $arghash->{language};
592             push(@{$arghash->{language}}, $value);
593
594         } elsif($type =~ /^sort/o) {
595             # sort and sort_dir modifiers
596             $arghash->{$type} = $value;
597
598         } else {
599             # append the search term to the term under construction
600             $search->{$type} =  {} unless $search->{$type};
601             $search->{$type}->{term} =  
602                 ($search->{$type}->{term}) ? $search->{$type}->{term} . " $value" : $value;
603         }
604     }
605
606     if($query) {
607         # This is the front part of the string before any special tokens were parsed. 
608         # Add this data to the default search class
609         my $type = $arghash->{default_class} || 'keyword';
610         $type = ($type eq '-') ? 'keyword' : $type;
611         $type = ($type !~ /^(title|author|keyword|subject|series)$/o) ? 'keyword' : $type;
612         $search->{$type} =  {} unless $search->{$type};
613         $search->{$type}->{term} =
614             ($search->{$type}->{term}) ? $search->{$type}->{term} . " $query" : $query;
615     }
616
617     # capture the original limit because the search method alters the limit internally
618     my $ol = $arghash->{limit};
619
620         my $sclient = OpenSRF::Utils::SettingsClient->new;
621
622     (my $method = $self->api_name) =~ s/\.query//o;
623
624     $method =~ s/multiclass/multiclass.staged/
625         if $sclient->config_value(apps => 'open-ils.search',
626             app_settings => 'use_staged_search') =~ /true/i;
627
628     $arghash->{preferred_language} = $U->get_org_locale($arghash->{org_unit})
629         unless $arghash->{preferred_language};
630
631         $method = $self->method_lookup($method);
632     my ($data) = $method->run($arghash, $docache);
633
634     $arghash->{limit} = $ol if $ol;
635     $data->{compiled_search} = $arghash;
636     $data->{query} = $orig_query;
637
638     $logger->info("compiled search is " . OpenSRF::Utils::JSON->perl2JSON($arghash));
639
640     return $data;
641 }
642
643 __PACKAGE__->register_method(
644         method          => 'cat_search_z_style_wrapper',
645         api_name        => 'open-ils.search.biblio.zstyle',
646         stream          => 1,
647         signature       => q/@see open-ils.search.biblio.multiclass/);
648
649 __PACKAGE__->register_method(
650         method          => 'cat_search_z_style_wrapper',
651         api_name        => 'open-ils.search.biblio.zstyle.staff',
652         stream          => 1,
653         signature       => q/@see open-ils.search.biblio.multiclass/);
654
655 sub cat_search_z_style_wrapper {
656         my $self = shift;
657         my $client = shift;
658         my $authtoken = shift;
659         my $args = shift;
660
661         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
662
663         my $ou = $cstore->request(
664                 'open-ils.cstore.direct.actor.org_unit.search',
665                 { parent_ou => undef }
666         )->gather(1);
667
668         my $result = { service => 'native-evergreen-catalog', records => [] };
669         my $searchhash = { limit => $$args{limit}, offset => $$args{offset}, org_unit => $ou->id };
670
671         $$searchhash{searches}{title}{term} = $$args{search}{title} if $$args{search}{title};
672         $$searchhash{searches}{author}{term} = $$args{search}{author} if $$args{search}{author};
673         $$searchhash{searches}{subject}{term} = $$args{search}{subject} if $$args{search}{subject};
674         $$searchhash{searches}{keyword}{term} = $$args{search}{keyword} if $$args{search}{keyword};
675
676         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{tcn} if $$args{search}{tcn};
677         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{isbn} if $$args{search}{isbn};
678         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{issn} if $$args{search}{issn};
679         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{publisher} if $$args{search}{publisher};
680         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{pubdate} if $$args{search}{pubdate};
681         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{item_type} if $$args{search}{item_type};
682
683         my $list = the_quest_for_knowledge( $self, $client, $searchhash );
684
685         if ($list->{count} > 0) {
686                 $result->{count} = $list->{count};
687
688                 my $records = $cstore->request(
689                         'open-ils.cstore.direct.biblio.record_entry.search.atomic',
690                         { id => [ map { ( $_->[0] ) } @{$list->{ids}} ] }
691                 )->gather(1);
692
693                 for my $rec ( @$records ) {
694                         
695                         my $u = OpenILS::Utils::ModsParser->new();
696                         $u->start_mods_batch( $rec->marc );
697                         my $mods = $u->finish_mods_batch();
698
699                         push @{ $result->{records} }, { mvr => $mods, marcxml => $rec->marc, bibid => $rec->id };
700
701                 }
702
703         }
704
705     $cstore->disconnect();
706         return $result;
707 }
708
709 # ----------------------------------------------------------------------------
710 # These are the main OPAC search methods
711 # ----------------------------------------------------------------------------
712
713 __PACKAGE__->register_method(
714         method          => 'the_quest_for_knowledge',
715         api_name                => 'open-ils.search.biblio.multiclass',
716         signature       => q/
717                 Performs a multi class biblio or metabib search
718                 @param searchhash A search object layed out like so:
719                         searches : { "$class" : "$value", ...}
720                         org_unit : The org id to focus the search at
721                         depth           : The org depth
722                         limit           : The search limit
723                         offset  : The search offset
724                         format  : The MARC format
725                         sort            : What field to sort the results on [ author | title | pubdate ]
726                         sort_dir        : What direction do we sort? [ asc | desc ]
727                 @return An object of the form 
728                         { "count" : $count, "ids" : [ [ $id, $relevancy, $total ], ...] }
729         /
730 );
731
732 __PACKAGE__->register_method(
733         method          => 'the_quest_for_knowledge',
734         api_name                => 'open-ils.search.biblio.multiclass.staff',
735         signature       => q/@see open-ils.search.biblio.multiclass/);
736 __PACKAGE__->register_method(
737         method          => 'the_quest_for_knowledge',
738         api_name                => 'open-ils.search.metabib.multiclass',
739         signature       => q/@see open-ils.search.biblio.multiclass/);
740 __PACKAGE__->register_method(
741         method          => 'the_quest_for_knowledge',
742         api_name                => 'open-ils.search.metabib.multiclass.staff',
743         signature       => q/@see open-ils.search.biblio.multiclass/);
744
745 sub the_quest_for_knowledge {
746         my( $self, $conn, $searchhash, $docache ) = @_;
747
748         return { count => 0 } unless $searchhash and
749                 ref $searchhash->{searches} eq 'HASH';
750
751         my $method = 'open-ils.storage.biblio.multiclass.search_fts';
752         my $ismeta = 0;
753         my @recs;
754
755         if($self->api_name =~ /metabib/) {
756                 $ismeta = 1;
757                 $method =~ s/biblio/metabib/o;
758         }
759
760
761         my $offset      = $searchhash->{offset} || 0;
762         my $limit       = $searchhash->{limit} || 10;
763         my $end         = $offset + $limit - 1;
764
765         # do some simple sanity checking
766         if(!$searchhash->{searches} or
767                 ( !grep { /^(?:title|author|subject|series|keyword)/ } keys %{$searchhash->{searches}} ) ) {
768                 return { count => 0 };
769         }
770
771
772         my $maxlimit = 5000;
773         $searchhash->{offset}   = 0;
774         $searchhash->{limit}            = $maxlimit;
775
776         return { count => 0 } if $offset > $maxlimit;
777
778         my @search;
779         push( @search, ($_ => $$searchhash{$_})) for (sort keys %$searchhash);
780         my $s = OpenSRF::Utils::JSON->perl2JSON(\@search);
781         my $ckey = $pfx . md5_hex($method . $s);
782
783         $logger->info("bib search for: $s");
784
785         $searchhash->{limit} -= $offset;
786
787
788     my $trim = 0;
789         my $result = ($docache) ? search_cache($ckey, $offset, $limit) : undef;
790
791         if(!$result) {
792
793                 $method .= ".staff" if($self->api_name =~ /staff/);
794                 $method .= ".atomic";
795         
796                 for (keys %$searchhash) { 
797                         delete $$searchhash{$_} 
798                                 unless defined $$searchhash{$_}; 
799                 }
800         
801                 $result = $U->storagereq( $method, %$searchhash );
802         $trim = 1;
803
804         } else { 
805                 $docache = 0; 
806         }
807
808         return {count => 0} unless ($result && $$result[0]);
809
810         @recs = @$result;
811
812         my $count = ($ismeta) ? $result->[0]->[3] : $result->[0]->[2];
813
814         if($docache) {
815                 # If we didn't get this data from the cache, put it into the cache
816                 # then return the correct offset of records
817                 $logger->debug("putting search cache $ckey\n");
818                 put_cache($ckey, $count, \@recs);
819         }
820
821     if($trim) {
822         # if we have the full set of data, trim out 
823         # the requested chunk based on limit and offset
824         my @t;
825         for ($offset..$end) {
826             last unless $recs[$_];
827             push(@t, $recs[$_]);
828         }
829         @recs = @t;
830     }
831
832         return { ids => \@recs, count => $count };
833 }
834
835
836 __PACKAGE__->register_method(
837         method          => 'staged_search',
838         api_name        => 'open-ils.search.biblio.multiclass.staged');
839 __PACKAGE__->register_method(
840         method          => 'staged_search',
841         api_name        => 'open-ils.search.biblio.multiclass.staged.staff',
842         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
843 __PACKAGE__->register_method(
844         method          => 'staged_search',
845         api_name        => 'open-ils.search.metabib.multiclass.staged',
846         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
847 __PACKAGE__->register_method(
848         method          => 'staged_search',
849         api_name        => 'open-ils.search.metabib.multiclass.staged.staff',
850         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
851
852 sub staged_search {
853         my($self, $conn, $search_hash, $docache) = @_;
854
855     my $method = ($self->api_name =~ /metabib/) ?
856         'open-ils.storage.metabib.multiclass.staged.search_fts':
857         'open-ils.storage.biblio.multiclass.staged.search_fts';
858
859     $method .= '.staff' if $self->api_name =~ /staff$/;
860     $method .= '.atomic';
861                 
862     return {count => 0} unless (
863         $search_hash and 
864         $search_hash->{searches} and 
865         scalar( keys %{$search_hash->{searches}} ));
866
867     my $search_duration;
868     my $user_offset = $search_hash->{offset} || 0; # user-specified offset
869     my $user_limit = $search_hash->{limit} || 10;
870     $user_offset = ($user_offset >= 0) ? $user_offset : 0;
871     $user_limit = ($user_limit >= 0) ? $user_limit : 10;
872
873
874     # we're grabbing results on a per-superpage basis, which means the 
875     # limit and offset should coincide with superpage boundaries
876     $search_hash->{offset} = 0;
877     $search_hash->{limit} = $superpage_size;
878
879     # force a well-known check_limit
880     $search_hash->{check_limit} = $superpage_size; 
881     # restrict total tested to superpage size * number of superpages
882     $search_hash->{core_limit} = $superpage_size * $max_superpages;
883
884     # Set the configured estimation strategy, defaults to 'inclusion'.
885         my $estimation_strategy = OpenSRF::Utils::SettingsClient
886         ->new
887         ->config_value(
888             apps => 'open-ils.search', app_settings => 'estimation_strategy'
889         ) || 'inclusion';
890         $search_hash->{estimation_strategy} = $estimation_strategy;
891
892     # pull any existing results from the cache
893     my $key = search_cache_key($method, $search_hash);
894     my $cache_data = $cache->get_cache($key) || {};
895
896     # keep retrieving results until we find enough to 
897     # fulfill the user-specified limit and offset
898     my $all_results = [];
899     my $page; # current superpage
900     my $est_hit_count = 0;
901     my $current_page_summary = {};
902     my $global_summary = {checked => 0, visible => 0, excluded => 0, deleted => 0, total => 0};
903     my $is_real_hit_count = 0;
904
905     for($page = 0; $page < $max_superpages; $page++) {
906
907         my $data = $cache_data->{$page};
908         my $results;
909         my $summary;
910
911         $logger->debug("staged search: analyzing superpage $page");
912
913         if($data) {
914             # this window of results is already cached
915             $logger->debug("staged search: found cached results");
916             $summary = $data->{summary};
917             $results = $data->{results};
918
919         } else {
920             # retrieve the window of results from the database
921             $logger->debug("staged search: fetching results from the database");
922             $search_hash->{skip_check} = $page * $superpage_size;
923             my $start = time;
924             $results = $U->storagereq($method, %$search_hash);
925             $search_duration = time - $start;
926             $logger->info("staged search: DB call took $search_duration seconds");
927             $summary = shift(@$results);
928
929             unless($summary) {
930                 $logger->info("search timed out: duration=$search_duration: params=".
931                     OpenSRF::Utils::JSON->perl2JSON($search_hash));
932                 return {count => 0};
933             }
934
935             my $hc = $summary->{estimated_hit_count} || $summary->{visible};
936             if($hc == 0) {
937                 $logger->info("search returned 0 results: duration=$search_duration: params=".
938                     OpenSRF::Utils::JSON->perl2JSON($search_hash));
939             }
940
941             # Create backwards-compatible result structures
942             if($self->api_name =~ /biblio/) {
943                 $results = [map {[$_->{id}]} @$results];
944             } else {
945                 $results = [map {[$_->{id}, $_->{rel}, $_->{record}]} @$results];
946             }
947
948             $results = [grep {defined $_->[0]} @$results];
949             cache_staged_search_page($key, $page, $summary, $results) if $docache;
950         }
951
952         $current_page_summary = $summary;
953
954         # add the new set of results to the set under construction
955         push(@$all_results, @$results);
956
957         my $current_count = scalar(@$all_results);
958
959         $est_hit_count = $summary->{estimated_hit_count} || $summary->{visible}
960             if $page == 0;
961
962         $logger->debug("staged search: located $current_count, with estimated hits=".
963             $summary->{estimated_hit_count}." : visible=".$summary->{visible}.", checked=".$summary->{checked});
964
965                 if (defined($summary->{estimated_hit_count})) {
966                         $global_summary->{checked} += $summary->{checked};
967                         $global_summary->{visible} += $summary->{visible};
968                         $global_summary->{excluded} += $summary->{excluded};
969                         $global_summary->{deleted} += $summary->{deleted};
970                         $global_summary->{total} = $summary->{total};
971                 }
972
973         # we've found all the possible hits
974         last if $current_count == $summary->{visible}
975             and not defined $summary->{estimated_hit_count};
976
977         # we've found enough results to satisfy the requested limit/offset
978         last if $current_count >= ($user_limit + $user_offset);
979
980         # we've scanned all possible hits
981         if($summary->{checked} < $superpage_size) {
982             $est_hit_count = scalar(@$all_results);
983             # we have all possible results in hand, so we know the final hit count
984             $is_real_hit_count = 1;
985             last;
986         }
987     }
988
989     my @results = grep {defined $_} @$all_results[$user_offset..($user_offset + $user_limit - 1)];
990
991         # refine the estimate if we have more than one superpage
992         if ($page > 0 and not $is_real_hit_count) {
993                 if ($global_summary->{checked} >= $global_summary->{total}) {
994                         $est_hit_count = $global_summary->{visible};
995                 } else {
996                         my $updated_hit_count = $U->storagereq(
997                                 'open-ils.storage.fts_paging_estimate',
998                                 $global_summary->{checked},
999                                 $global_summary->{visible},
1000                                 $global_summary->{excluded},
1001                                 $global_summary->{deleted},
1002                                 $global_summary->{total}
1003                         );
1004                         $est_hit_count = $updated_hit_count->{$estimation_strategy};
1005                 }
1006         }
1007
1008     return {
1009         count => $est_hit_count,
1010         core_limit => $search_hash->{core_limit},
1011         superpage_size => $search_hash->{check_limit},
1012         superpage_summary => $current_page_summary,
1013         ids => \@results
1014     };
1015 }
1016
1017 # creates a unique token to represent the query in the cache
1018 sub search_cache_key {
1019     my $method = shift;
1020     my $search_hash = shift;
1021         my @sorted;
1022     for my $key (sort keys %$search_hash) {
1023             push(@sorted, ($key => $$search_hash{$key})) 
1024             unless $key eq 'limit' or 
1025                 $key eq 'offset' or 
1026                 $key eq 'skip_check';
1027     }
1028         my $s = OpenSRF::Utils::JSON->perl2JSON(\@sorted);
1029         return $pfx . md5_hex($method . $s);
1030 }
1031
1032 sub cache_staged_search_page {
1033     # puts this set of results into the cache
1034     my($key, $page, $summary, $results) = @_;
1035     my $data = $cache->get_cache($key);
1036     $data ||= {};
1037     $data->{$page} = {
1038         summary => $summary,
1039         results => $results
1040     };
1041
1042     $logger->info("staged search: cached with key=$key, superpage=$page, estimated=".
1043         $summary->{estimated_hit_count}.", visible=".$summary->{visible});
1044
1045     $cache->put_cache($key, $data, $cache_timeout);
1046 }
1047
1048 sub search_cache {
1049
1050         my $key         = shift;
1051         my $offset      = shift;
1052         my $limit       = shift;
1053         my $start       = $offset;
1054         my $end         = $offset + $limit - 1;
1055
1056         $logger->debug("searching cache for $key : $start..$end\n");
1057
1058         return undef unless $cache;
1059         my $data = $cache->get_cache($key);
1060
1061         return undef unless $data;
1062
1063         my $count = $data->[0];
1064         $data = $data->[1];
1065
1066         return undef unless $offset < $count;
1067
1068         my @result;
1069         for( my $i = $offset; $i <= $end; $i++ ) {
1070                 last unless my $d = $$data[$i];
1071                 push( @result, $d );
1072         }
1073
1074         $logger->debug("search_cache found ".scalar(@result)." items for count=$count, start=$start, end=$end");
1075
1076         return \@result;
1077 }
1078
1079
1080 sub put_cache {
1081         my( $key, $count, $data ) = @_;
1082         return undef unless $cache;
1083         $logger->debug("search_cache putting ".
1084                 scalar(@$data)." items at key $key with timeout $cache_timeout");
1085         $cache->put_cache($key, [ $count, $data ], $cache_timeout);
1086 }
1087
1088
1089
1090
1091
1092
1093 __PACKAGE__->register_method(
1094         method  => "biblio_mrid_to_modsbatch_batch",
1095         api_name        => "open-ils.search.biblio.metarecord.mods_slim.batch.retrieve");
1096
1097 sub biblio_mrid_to_modsbatch_batch {
1098         my( $self, $client, $mrids) = @_;
1099         warn "Performing mrid_to_modsbatch_batch...";
1100         my @mods;
1101         my $method = $self->method_lookup("open-ils.search.biblio.metarecord.mods_slim.retrieve");
1102         for my $id (@$mrids) {
1103                 next unless defined $id;
1104                 my ($m) = $method->run($id);
1105                 push @mods, $m;
1106         }
1107         return \@mods;
1108 }
1109
1110
1111 __PACKAGE__->register_method(
1112         method  => "biblio_mrid_to_modsbatch",
1113         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve",
1114         notes           => <<"  NOTES");
1115         Returns the mvr associated with a given metarecod. If none exists, 
1116         it is created.
1117         NOTES
1118
1119 __PACKAGE__->register_method(
1120         method  => "biblio_mrid_to_modsbatch",
1121         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve.staff",
1122         notes           => <<"  NOTES");
1123         Returns the mvr associated with a given metarecod. If none exists, 
1124         it is created.
1125         NOTES
1126
1127 sub biblio_mrid_to_modsbatch {
1128         my( $self, $client, $mrid, $args) = @_;
1129
1130         warn "Grabbing mvr for $mrid\n";
1131
1132         my ($mr, $evt) = _grab_metarecord($mrid);
1133         return $evt unless $mr;
1134
1135         my $mvr = biblio_mrid_check_mvr($self, $client, $mr);
1136         $mvr = biblio_mrid_make_modsbatch( $self, $client, $mr ) unless $mvr;
1137
1138         return $mvr unless ref($args);  
1139
1140         # Here we find the lead record appropriate for the given filters 
1141         # and use that for the title and author of the metarecord
1142         my $format      = $$args{format};
1143         my $org         = $$args{org};
1144         my $depth       = $$args{depth};
1145
1146         return $mvr unless $format or $org or $depth;
1147
1148         my $method = "open-ils.storage.ordered.metabib.metarecord.records";
1149         $method = "$method.staff" if $self->api_name =~ /staff/o; 
1150
1151         my $rec = $U->storagereq($method, $format, $org, $depth, 1);
1152
1153         if( my $mods = $U->record_to_mvr($rec) ) {
1154
1155                 $mvr->title($mods->title);
1156                 $mvr->title($mods->author);
1157                 $logger->debug("mods_slim updating title and ".
1158                         "author in mvr with ".$mods->title." : ".$mods->author);
1159         }
1160
1161         return $mvr;
1162 }
1163
1164 # converts a metarecord to an mvr
1165 sub _mr_to_mvr {
1166         my $mr = shift;
1167         my $perl = OpenSRF::Utils::JSON->JSON2perl($mr->mods());
1168         return Fieldmapper::metabib::virtual_record->new($perl);
1169 }
1170
1171 # checks to see if a metarecord has mods, if so returns true;
1172
1173 __PACKAGE__->register_method(
1174         method  => "biblio_mrid_check_mvr",
1175         api_name        => "open-ils.search.biblio.metarecord.mods_slim.check",
1176         notes           => <<"  NOTES");
1177         Takes a metarecord ID or a metarecord object and returns true
1178         if the metarecord already has an mvr associated with it.
1179         NOTES
1180
1181 sub biblio_mrid_check_mvr {
1182         my( $self, $client, $mrid ) = @_;
1183         my $mr; 
1184
1185         my $evt;
1186         if(ref($mrid)) { $mr = $mrid; } 
1187         else { ($mr, $evt) = _grab_metarecord($mrid); }
1188         return $evt if $evt;
1189
1190         warn "Checking mvr for mr " . $mr->id . "\n";
1191
1192         return _mr_to_mvr($mr) if $mr->mods();
1193         return undef;
1194 }
1195
1196 sub _grab_metarecord {
1197         my $mrid = shift;
1198         #my $e = OpenILS::Utils::Editor->new;
1199         my $e = new_editor();
1200         my $mr = $e->retrieve_metabib_metarecord($mrid) or return ( undef, $e->event );
1201         return ($mr);
1202 }
1203
1204
1205 __PACKAGE__->register_method(
1206         method  => "biblio_mrid_make_modsbatch",
1207         api_name        => "open-ils.search.biblio.metarecord.mods_slim.create",
1208         notes           => <<"  NOTES");
1209         Takes either a metarecord ID or a metarecord object.
1210         Forces the creations of an mvr for the given metarecord.
1211         The created mvr is returned.
1212         NOTES
1213
1214 sub biblio_mrid_make_modsbatch {
1215         my( $self, $client, $mrid ) = @_;
1216
1217         #my $e = OpenILS::Utils::Editor->new;
1218         my $e = new_editor();
1219
1220         my $mr;
1221         if( ref($mrid) ) {
1222                 $mr = $mrid;
1223                 $mrid = $mr->id;
1224         } else {
1225                 $mr = $e->retrieve_metabib_metarecord($mrid) 
1226                         or return $e->event;
1227         }
1228
1229         my $masterid = $mr->master_record;
1230         $logger->info("creating new mods batch for metarecord=$mrid, master record=$masterid");
1231
1232         my $ids = $U->storagereq(
1233                 'open-ils.storage.ordered.metabib.metarecord.records.staff.atomic', $mrid);
1234         return undef unless @$ids;
1235
1236         my $master = $e->retrieve_biblio_record_entry($masterid)
1237                 or return $e->event;
1238
1239         # start the mods batch
1240         my $u = OpenILS::Utils::ModsParser->new();
1241         $u->start_mods_batch( $master->marc );
1242
1243         # grab all of the sub-records and shove them into the batch
1244         my @ids = grep { $_ ne $masterid } @$ids;
1245         #my $subrecs = (@ids) ? $e->batch_retrieve_biblio_record_entry(\@ids) : [];
1246
1247         my $subrecs = [];
1248         if(@$ids) {
1249                 for my $i (@$ids) {
1250                         my $r = $e->retrieve_biblio_record_entry($i);
1251                         push( @$subrecs, $r ) if $r;
1252                 }
1253         }
1254
1255         for(@$subrecs) {
1256                 $logger->debug("adding record ".$_->id." to mods batch for metarecord=$mrid");
1257                 $u->push_mods_batch( $_->marc ) if $_->marc;
1258         }
1259
1260
1261         # finish up and send to the client
1262         my $mods = $u->finish_mods_batch();
1263         $mods->doc_id($mrid);
1264         $client->respond_complete($mods);
1265
1266
1267         # now update the mods string in the db
1268         my $string = OpenSRF::Utils::JSON->perl2JSON($mods->decast);
1269         $mr->mods($string);
1270
1271         #$e = OpenILS::Utils::Editor->new(xact => 1);
1272         $e = new_editor(xact => 1);
1273         $e->update_metabib_metarecord($mr) 
1274                 or $logger->error("Error setting mods text on metarecord $mrid : " . Dumper($e->event));
1275         $e->finish;
1276
1277         return undef;
1278 }
1279
1280
1281
1282
1283 # converts a mr id into a list of record ids
1284
1285 __PACKAGE__->register_method(
1286         method  => "biblio_mrid_to_record_ids",
1287         api_name        => "open-ils.search.biblio.metarecord_to_records",
1288 );
1289
1290 __PACKAGE__->register_method(
1291         method  => "biblio_mrid_to_record_ids",
1292         api_name        => "open-ils.search.biblio.metarecord_to_records.staff",
1293 );
1294
1295 sub biblio_mrid_to_record_ids {
1296         my( $self, $client, $mrid, $args ) = @_;
1297
1298         my $format      = $$args{format};
1299         my $org         = $$args{org};
1300         my $depth       = $$args{depth};
1301
1302         my $method = "open-ils.storage.ordered.metabib.metarecord.records.atomic";
1303         $method =~ s/atomic/staff\.atomic/o if $self->api_name =~ /staff/o; 
1304         my $recs = $U->storagereq($method, $mrid, $format, $org, $depth);
1305
1306         return { count => scalar(@$recs), ids => $recs };
1307 }
1308
1309
1310 __PACKAGE__->register_method(
1311         method  => "biblio_record_to_marc_html",
1312         api_name        => "open-ils.search.biblio.record.html" );
1313
1314 __PACKAGE__->register_method(
1315         method  => "biblio_record_to_marc_html",
1316         api_name        => "open-ils.search.authority.to_html" );
1317
1318 my $parser = XML::LibXML->new();
1319 my $xslt = XML::LibXSLT->new();
1320 my $marc_sheet;
1321 my $slim_marc_sheet;
1322 my $settings_client = OpenSRF::Utils::SettingsClient->new();
1323
1324 sub biblio_record_to_marc_html {
1325         my($self, $client, $recordid, $slim, $marcxml) = @_;
1326
1327     my $sheet;
1328         my $dir = $settings_client->config_value("dirs", "xsl");
1329
1330     if($slim) {
1331         unless($slim_marc_sheet) {
1332                     my $xsl = $settings_client->config_value(
1333                             "apps", "open-ils.search", "app_settings", 'marc_html_xsl_slim');
1334             if($xsl) {
1335                         $xsl = $parser->parse_file("$dir/$xsl");
1336                         $slim_marc_sheet = $xslt->parse_stylesheet($xsl);
1337             }
1338         }
1339         $sheet = $slim_marc_sheet;
1340     }
1341
1342     unless($sheet) {
1343         unless($marc_sheet) {
1344             my $xsl_key = ($slim) ? 'marc_html_xsl_slim' : 'marc_html_xsl';
1345                     my $xsl = $settings_client->config_value(
1346                             "apps", "open-ils.search", "app_settings", 'marc_html_xsl');
1347                     $xsl = $parser->parse_file("$dir/$xsl");
1348                     $marc_sheet = $xslt->parse_stylesheet($xsl);
1349         }
1350         $sheet = $marc_sheet;
1351     }
1352
1353     my $record;
1354     unless($marcxml) {
1355         my $e = new_editor();
1356         if($self->api_name =~ /authority/) {
1357             $record = $e->retrieve_authority_record_entry($recordid)
1358                 or return $e->event;
1359         } else {
1360             $record = $e->retrieve_biblio_record_entry($recordid)
1361                 or return $e->event;
1362         }
1363         $marcxml = $record->marc;
1364     }
1365
1366         my $xmldoc = $parser->parse_string($marcxml);
1367         my $html = $sheet->transform($xmldoc);
1368         return $html->documentElement->toString();
1369 }
1370
1371
1372
1373 __PACKAGE__->register_method(
1374         method  => "retrieve_all_copy_statuses",
1375         api_name        => "open-ils.search.config.copy_status.retrieve.all" );
1376
1377 sub retrieve_all_copy_statuses {
1378         my( $self, $client ) = @_;
1379         return new_editor()->retrieve_all_config_copy_status();
1380 }
1381
1382
1383 __PACKAGE__->register_method(
1384         method  => "copy_counts_per_org",
1385         api_name        => "open-ils.search.biblio.copy_counts.retrieve");
1386
1387 __PACKAGE__->register_method(
1388         method  => "copy_counts_per_org",
1389         api_name        => "open-ils.search.biblio.copy_counts.retrieve.staff");
1390
1391 sub copy_counts_per_org {
1392         my( $self, $client, $record_id ) = @_;
1393
1394         warn "Retreiveing copy copy counts for record $record_id and method " . $self->api_name . "\n";
1395
1396         my $method = "open-ils.storage.biblio.record_entry.global_copy_count.atomic";
1397         if($self->api_name =~ /staff/) { $method =~ s/atomic/staff\.atomic/; }
1398
1399         my $counts = $apputils->simple_scalar_request(
1400                 "open-ils.storage", $method, $record_id );
1401
1402         $counts = [ sort {$a->[0] <=> $b->[0]} @$counts ];
1403         return $counts;
1404 }
1405
1406
1407 __PACKAGE__->register_method(
1408         method          => "copy_count_summary",
1409         api_name        => "open-ils.search.biblio.copy_counts.summary.retrieve",
1410         notes           => <<"  NOTES");
1411         returns an array of these:
1412                 [ org_id, callnumber_label, <status1_count>, <status2_count>,...]
1413                 where statusx is a copy status name.  the statuses are sorted
1414                 by id.
1415         NOTES
1416
1417 sub copy_count_summary {
1418         my( $self, $client, $rid, $org, $depth ) = @_;
1419         $org ||= 1;
1420         $depth ||= 0;
1421     my $data = $U->storagereq(
1422                 'open-ils.storage.biblio.record_entry.status_copy_count.atomic', $rid, $org, $depth );
1423
1424     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1425 }
1426
1427 __PACKAGE__->register_method(
1428         method          => "copy_location_count_summary",
1429         api_name        => "open-ils.search.biblio.copy_location_counts.summary.retrieve",
1430         notes           => <<"  NOTES");
1431         returns an array of these:
1432                 [ org_id, callnumber_label, copy_location, <status1_count>, <status2_count>,...]
1433                 where statusx is a copy status name.  the statuses are sorted
1434                 by id.
1435         NOTES
1436
1437 sub copy_location_count_summary {
1438         my( $self, $client, $rid, $org, $depth ) = @_;
1439         $org ||= 1;
1440         $depth ||= 0;
1441     my $data = $U->storagereq(
1442                 'open-ils.storage.biblio.record_entry.status_copy_location_count.atomic', $rid, $org, $depth );
1443
1444     return [ sort { $a->[1] cmp $b->[1] || $a->[2] cmp $b->[2] } @$data ];
1445 }
1446
1447 __PACKAGE__->register_method(
1448         method          => "copy_count_location_summary",
1449         api_name        => "open-ils.search.biblio.copy_counts.location.summary.retrieve",
1450         notes           => <<"  NOTES");
1451         returns an array of these:
1452                 [ org_id, callnumber_label, <status1_count>, <status2_count>,...]
1453                 where statusx is a copy status name.  the statuses are sorted
1454                 by id.
1455         NOTES
1456
1457 sub copy_count_location_summary {
1458         my( $self, $client, $rid, $org, $depth ) = @_;
1459         $org ||= 1;
1460         $depth ||= 0;
1461     my $data = $U->storagereq(
1462         'open-ils.storage.biblio.record_entry.status_copy_location_count.atomic', $rid, $org, $depth );
1463     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1464 }
1465
1466
1467 __PACKAGE__->register_method(
1468         method          => "marc_search",
1469         api_name        => "open-ils.search.biblio.marc.staff");
1470
1471 __PACKAGE__->register_method(
1472         method          => "marc_search",
1473         api_name        => "open-ils.search.biblio.marc",
1474         notes           => <<"  NOTES");
1475                 Example:
1476                 open-ils.storage.biblio.full_rec.multi_search.atomic 
1477                 { "searches": [{"term":"harry","restrict": [{"tag":245,"subfield":"a"}]}], "org_unit": 1,
1478         "limit":5,"sort":"author","item_type":"g"}
1479         NOTES
1480
1481 sub marc_search {
1482         my( $self, $conn, $args, $limit, $offset ) = @_;
1483
1484         my $method = 'open-ils.storage.biblio.full_rec.multi_search';
1485         $method .= ".staff" if $self->api_name =~ /staff/;
1486         $method .= ".atomic";
1487
1488         $limit ||= 10;
1489         $offset ||= 0;
1490
1491         my @search;
1492         push( @search, ($_ => $$args{$_}) ) for (sort keys %$args);
1493         my $ckey = $pfx . md5_hex($method . OpenSRF::Utils::JSON->perl2JSON(\@search));
1494
1495         my $recs = search_cache($ckey, $offset, $limit);
1496
1497         if(!$recs) {
1498                 $recs = $U->storagereq($method, %$args) || [];
1499                 if( $recs ) {
1500                         put_cache($ckey, scalar(@$recs), $recs);
1501                         $recs = [ @$recs[$offset..($offset + ($limit - 1))] ];
1502                 } else {
1503                         $recs = [];
1504                 }
1505         }
1506
1507         my $count = 0;
1508         $count = $recs->[0]->[2] if $recs->[0] and $recs->[0]->[2];
1509         my @recs = map { $_->[0] } @$recs;
1510
1511         return { ids => \@recs, count => $count };
1512 }
1513
1514
1515 __PACKAGE__->register_method(
1516         method  => "biblio_search_isbn",
1517         api_name        => "open-ils.search.biblio.isbn",
1518 );
1519
1520 sub biblio_search_isbn { 
1521         my( $self, $client, $isbn ) = @_;
1522         $logger->debug("Searching ISBN $isbn");
1523         my $e = new_editor();
1524         my $recs = $U->storagereq(
1525                 'open-ils.storage.id_list.biblio.record_entry.search.isbn.atomic', $isbn );
1526         return { ids => $recs, count => scalar(@$recs) };
1527 }
1528
1529
1530 __PACKAGE__->register_method(
1531         method  => "biblio_search_issn",
1532         api_name        => "open-ils.search.biblio.issn",
1533 );
1534
1535 sub biblio_search_issn { 
1536         my( $self, $client, $issn ) = @_;
1537         $logger->debug("Searching ISSN $issn");
1538         my $e = new_editor();
1539         $issn =~ s/-/ /g;
1540         my $recs = $U->storagereq(
1541                 'open-ils.storage.id_list.biblio.record_entry.search.issn.atomic', $issn );
1542         return { ids => $recs, count => scalar(@$recs) };
1543 }
1544
1545
1546
1547
1548 __PACKAGE__->register_method(
1549         method  => "fetch_mods_by_copy",
1550         api_name        => "open-ils.search.biblio.mods_from_copy",
1551 );
1552
1553 sub fetch_mods_by_copy {
1554         my( $self, $client, $copyid ) = @_;
1555         my ($record, $evt) = $apputils->fetch_record_by_copy( $copyid );
1556         return $evt if $evt;
1557         return OpenILS::Event->new('ITEM_NOT_CATALOGED') unless $record->marc;
1558         return $apputils->record_to_mvr($record);
1559 }
1560
1561
1562
1563 # -------------------------------------------------------------------------------------
1564
1565 __PACKAGE__->register_method(
1566         method  => "cn_browse",
1567         api_name        => "open-ils.search.callnumber.browse.target",
1568         notes           => "Starts a callnumber browse"
1569         );
1570
1571 __PACKAGE__->register_method(
1572         method  => "cn_browse",
1573         api_name        => "open-ils.search.callnumber.browse.page_up",
1574         notes           => "Returns the previous page of callnumbers", 
1575         );
1576
1577 __PACKAGE__->register_method(
1578         method  => "cn_browse",
1579         api_name        => "open-ils.search.callnumber.browse.page_down",
1580         notes           => "Returns the next page of callnumbers", 
1581         );
1582
1583
1584 # RETURNS array of arrays like so: label, owning_lib, record, id
1585 sub cn_browse {
1586         my( $self, $client, @params ) = @_;
1587         my $method;
1588
1589         $method = 'open-ils.storage.asset.call_number.browse.target.atomic' 
1590                 if( $self->api_name =~ /target/ );
1591         $method = 'open-ils.storage.asset.call_number.browse.page_up.atomic'
1592                 if( $self->api_name =~ /page_up/ );
1593         $method = 'open-ils.storage.asset.call_number.browse.page_down.atomic'
1594                 if( $self->api_name =~ /page_down/ );
1595
1596         return $apputils->simplereq( 'open-ils.storage', $method, @params );
1597 }
1598 # -------------------------------------------------------------------------------------
1599
1600 __PACKAGE__->register_method(
1601         method => "fetch_cn",
1602     authoritative => 1,
1603         api_name => "open-ils.search.callnumber.retrieve",
1604         notes           => "retrieves a callnumber based on ID",
1605         );
1606
1607 sub fetch_cn {
1608         my( $self, $client, $id ) = @_;
1609         my( $cn, $evt ) = $apputils->fetch_callnumber( $id );
1610         return $evt if $evt;
1611         return $cn;
1612 }
1613
1614 __PACKAGE__->register_method (
1615         method          => "fetch_copy_by_cn",
1616         api_name                => 'open-ils.search.copies_by_call_number.retrieve',
1617         signature       => q/
1618                 Returns an array of copy id's by callnumber id
1619                 @param cnid The callnumber id
1620                 @return An array of copy ids
1621         /
1622 );
1623
1624 sub fetch_copy_by_cn {
1625         my( $self, $conn, $cnid ) = @_;
1626         return $U->cstorereq(
1627                 'open-ils.cstore.direct.asset.copy.id_list.atomic', 
1628                 { call_number => $cnid, deleted => 'f' } );
1629 }
1630
1631 __PACKAGE__->register_method (
1632         method          => 'fetch_cn_by_info',
1633         api_name                => 'open-ils.search.call_number.retrieve_by_info',
1634         signature       => q/
1635                 @param label The callnumber label
1636                 @param record The record the cn is attached to
1637                 @param org The owning library of the cn
1638                 @return The callnumber object
1639         /
1640 );
1641
1642
1643 sub fetch_cn_by_info {
1644         my( $self, $conn, $label, $record, $org ) = @_;
1645         return $U->cstorereq(
1646                 'open-ils.cstore.direct.asset.call_number.search',
1647                 { label => $label, record => $record, owning_lib => $org, deleted => 'f' });
1648 }
1649
1650
1651                 
1652
1653
1654 __PACKAGE__->register_method (
1655         method => 'bib_extras',
1656         api_name => 'open-ils.search.biblio.lit_form_map.retrieve.all');
1657 __PACKAGE__->register_method (
1658         method => 'bib_extras',
1659         api_name => 'open-ils.search.biblio.item_form_map.retrieve.all');
1660 __PACKAGE__->register_method (
1661         method => 'bib_extras',
1662         api_name => 'open-ils.search.biblio.item_type_map.retrieve.all');
1663 __PACKAGE__->register_method (
1664         method => 'bib_extras',
1665         api_name => 'open-ils.search.biblio.bib_level_map.retrieve.all');
1666 __PACKAGE__->register_method (
1667         method => 'bib_extras',
1668         api_name => 'open-ils.search.biblio.audience_map.retrieve.all');
1669
1670 sub bib_extras {
1671         my $self = shift;
1672
1673         my $e = new_editor();
1674
1675         return $e->retrieve_all_config_lit_form_map()
1676                 if( $self->api_name =~ /lit_form/ );
1677
1678         return $e->retrieve_all_config_item_form_map()
1679                 if( $self->api_name =~ /item_form_map/ );
1680
1681         return $e->retrieve_all_config_item_type_map()
1682                 if( $self->api_name =~ /item_type_map/ );
1683
1684         return $e->retrieve_all_config_bib_level_map()
1685                 if( $self->api_name =~ /bib_level_map/ );
1686
1687         return $e->retrieve_all_config_audience_map()
1688                 if( $self->api_name =~ /audience_map/ );
1689
1690         return [];
1691 }
1692
1693
1694
1695 __PACKAGE__->register_method(
1696         method  => 'fetch_slim_record',
1697         api_name        => 'open-ils.search.biblio.record_entry.slim.retrieve',
1698         signature=> q/
1699                 Returns a biblio.record_entry without the attached marcxml
1700         /
1701 );
1702
1703 sub fetch_slim_record {
1704         my( $self, $conn, $ids ) = @_;
1705
1706         #my $editor = OpenILS::Utils::Editor->new;
1707         my $editor = new_editor();
1708         my @res;
1709         for( @$ids ) {
1710                 return $editor->event unless
1711                         my $r = $editor->retrieve_biblio_record_entry($_);
1712                 $r->clear_marc;
1713                 push(@res, $r);
1714         }
1715         return \@res;
1716 }
1717
1718
1719
1720 __PACKAGE__->register_method(
1721         method => 'rec_to_mr_rec_descriptors',
1722         api_name        => 'open-ils.search.metabib.record_to_descriptors',
1723         signature       => q/
1724                 specialized method...
1725                 Given a biblio record id or a metarecord id, 
1726                 this returns a list of metabib.record_descriptor
1727                 objects that live within the same metarecord
1728                 @param args Object of args including:
1729         /
1730 );
1731
1732 sub rec_to_mr_rec_descriptors {
1733         my( $self, $conn, $args ) = @_;
1734
1735         my $rec = $$args{record};
1736         my $mrec        = $$args{metarecord};
1737         my $item_forms = $$args{item_forms};
1738         my $item_types  = $$args{item_types};
1739         my $item_lang   = $$args{item_lang};
1740
1741         my $e = new_editor();
1742         my $recs;
1743
1744         if( !$mrec ) {
1745                 my $map = $e->search_metabib_metarecord_source_map({source => $rec});
1746                 return $e->event unless @$map;
1747                 $mrec = $$map[0]->metarecord;
1748         }
1749
1750         $recs = $e->search_metabib_metarecord_source_map({metarecord => $mrec});
1751         return $e->event unless @$recs;
1752
1753         my @recs = map { $_->source } @$recs;
1754         my $search = { record => \@recs };
1755         $search->{item_form} = $item_forms if $item_forms and @$item_forms;
1756         $search->{item_type} = $item_types if $item_types and @$item_types;
1757         $search->{item_lang} = $item_lang if $item_lang;
1758
1759         my $desc = $e->search_metabib_record_descriptor($search);
1760
1761         return { metarecord => $mrec, descriptors => $desc };
1762 }
1763
1764
1765
1766
1767 __PACKAGE__->register_method(
1768         method => 'copies_created_on',  
1769 );
1770
1771
1772 sub copies_created_on {
1773         my( $self, $conn, $auth, $org, $date ) = @_;
1774         my $e = new_editor(authtoken=>$auth);
1775         return $e->event unless $e->checkauth;
1776 }
1777
1778
1779 __PACKAGE__->register_method(
1780         method => 'fetch_age_protect',
1781         api_name => 'open-ils.search.copy.age_protect.retrieve.all',
1782 );
1783
1784 sub fetch_age_protect {
1785         return new_editor()->retrieve_all_config_rule_age_hold_protect();
1786 }
1787
1788
1789 __PACKAGE__->register_method(
1790         method => 'copies_by_cn_label',
1791         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label',
1792 );
1793
1794 __PACKAGE__->register_method(
1795         method => 'copies_by_cn_label',
1796         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label.staff',
1797 );
1798
1799 sub copies_by_cn_label {
1800         my( $self, $conn, $record, $label, $circ_lib ) = @_;
1801         my $e = new_editor();
1802         my $cns = $e->search_asset_call_number({record => $record, label => $label, deleted => 'f'}, {idlist=>1});
1803         return [] unless @$cns;
1804
1805         # show all non-deleted copies in the staff client ...
1806         if ($self->api_name =~ /staff$/o) {
1807                 return $e->search_asset_copy({call_number => $cns, circ_lib => $circ_lib, deleted => 'f'}, {idlist=>1});
1808         }
1809
1810         # ... otherwise, grab the copies ...
1811         my $copies = $e->search_asset_copy(
1812                 [ {call_number => $cns, circ_lib => $circ_lib, deleted => 'f', opac_visible => 't'},
1813                   {flesh => 1, flesh_fields => { acp => [ qw/location status/] } }
1814                 ]
1815         );
1816
1817         # ... and test for location and status visibility
1818         return [ map { ($U->is_true($_->location->opac_visible) && $U->is_true($_->status->opac_visible)) ? ($_->id) : () } @$copies ];
1819 }
1820
1821
1822
1823 1;
1824
1825