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