]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Biblio.pm
stop looking when we have checked all of the possible hits for visibility. no longer...
[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 $PAGE_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} = $PAGE_SIZE;
759     $search_hash->{check_limit} = $PAGE_SIZE; # force a well-known check_limit
760
761     # pull any existing results from the cache
762     my $key = search_cache_key($method, $search_hash);
763     my $cache_data = $cache->get_cache($key) || {};
764
765     # keep retrieving results until we find enough to 
766     # fulfill the user-specified limit and offset
767     my $all_results = [];
768     my $page; # current superpage
769     my $est_hit_count;
770
771     for($page = 0; $page < $SEARCH_PAGES; $page++) {
772
773         my $data = $cache_data->{$page};
774         my $results;
775         my $summary;
776
777         $logger->debug("staged search: analyzing superpage $page");
778
779         if($data) {
780             # this window of results is already cached
781             $logger->debug("staged search: found cached results");
782             $summary = $data->{summary};
783             $results = $data->{results};
784
785         } else {
786             # retrieve the window of results from the database
787             $logger->debug("staged search: fetching results from the database");
788             $search_hash->{skip_check} = $page * $PAGE_SIZE;
789             $results = $U->storagereq($method, %$search_hash);
790             $summary = shift(@$results);
791
792             # Clean up the raw search results
793             if($self->api_name =~ /biblio/) {
794                 $results = [map {$_->{id}} @$results];
795             } else {
796                 delete $_->{rel} for @$results;
797             }
798
799             cache_staged_search_page($key, $page, $summary, $results) unless $nocache;
800         }
801
802         # add the new set of results to the set under construction
803         push(@$all_results, grep {defined $_} @$results);
804
805         my $current_count = scalar(@$all_results);
806
807         $est_hit_count = $summary->{estimated_hit_count} || $summary->{visible}
808             if $page == 0;
809
810         $logger->debug("staged search: located $current_count, with estimated hits=".
811             $summary->{estimated_hit_count}." : visible=".$summary->{visible}.", checked=".$summary->{checked});
812
813         # we've found all the possible hits
814         last if $current_count == $summary->{visible}
815             and not defined $summary->{estimated_hit_count};
816
817         # we've found enough results to satisfy the requested limit/offset
818         last if $current_count >= ($user_limit + $user_offset);
819
820         # we've scanned all possible hits
821         last if $summary->{checked} < $PAGE_SIZE;
822     }
823
824     # calculate the average estimated hit count from the data we've collected thus far
825     my @results = grep {defined $_} @$all_results[$user_offset..($user_offset + $user_limit - 1)];
826
827     return {
828         count => $est_hit_count,
829         results => \@results
830     };
831 }
832
833 # creates a unique token to represent the query in the cache
834 sub search_cache_key {
835     my $method = shift;
836     my $search_hash = shift;
837         my @sorted;
838     for my $key (sort keys %$search_hash) {
839             push(@sorted, ($key => $$search_hash{$key})) 
840             unless $key eq 'limit' or 
841                 $key eq 'offset' or 
842                 $key eq 'skip_check';
843     }
844         my $s = OpenSRF::Utils::JSON->perl2JSON(\@sorted);
845         return $pfx . md5_hex($method . $s);
846 }
847
848 sub cache_staged_search_page {
849     # puts this set of results into the cache
850     my($key, $page, $summary, $results) = @_;
851     my $data = $cache->get_cache($key);
852     $data ||= {};
853     $data->{$page} = {
854         summary => $summary,
855         results => $results
856     };
857
858     $logger->info("staged search: cached with key=$key, superpage=$page, estimated=".
859         $summary->{estimated_hit_count}.", visible=".$summary->{visible});
860
861     $cache->put_cache($key, $data);
862 }
863
864 sub search_cache {
865
866         my $key         = shift;
867         my $offset      = shift;
868         my $limit       = shift;
869         my $start       = $offset;
870         my $end         = $offset + $limit - 1;
871
872         $logger->debug("searching cache for $key : $start..$end\n");
873
874         return undef unless $cache;
875         my $data = $cache->get_cache($key);
876
877         return undef unless $data;
878
879         my $count = $data->[0];
880         $data = $data->[1];
881
882         return undef unless $offset < $count;
883
884         my @result;
885         for( my $i = $offset; $i <= $end; $i++ ) {
886                 last unless my $d = $$data[$i];
887                 push( @result, $d );
888         }
889
890         $logger->debug("search_cache found ".scalar(@result)." items for count=$count, start=$start, end=$end");
891
892         return \@result;
893 }
894
895
896 sub put_cache {
897         my( $key, $count, $data ) = @_;
898         return undef unless $cache;
899         $logger->debug("search_cache putting ".
900                 scalar(@$data)." items at key $key with timeout $cache_timeout");
901         $cache->put_cache($key, [ $count, $data ], $cache_timeout);
902 }
903
904
905
906
907
908
909 __PACKAGE__->register_method(
910         method  => "biblio_mrid_to_modsbatch_batch",
911         api_name        => "open-ils.search.biblio.metarecord.mods_slim.batch.retrieve");
912
913 sub biblio_mrid_to_modsbatch_batch {
914         my( $self, $client, $mrids) = @_;
915         warn "Performing mrid_to_modsbatch_batch...";
916         my @mods;
917         my $method = $self->method_lookup("open-ils.search.biblio.metarecord.mods_slim.retrieve");
918         for my $id (@$mrids) {
919                 next unless defined $id;
920                 my ($m) = $method->run($id);
921                 push @mods, $m;
922         }
923         return \@mods;
924 }
925
926
927 __PACKAGE__->register_method(
928         method  => "biblio_mrid_to_modsbatch",
929         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve",
930         notes           => <<"  NOTES");
931         Returns the mvr associated with a given metarecod. If none exists, 
932         it is created.
933         NOTES
934
935 __PACKAGE__->register_method(
936         method  => "biblio_mrid_to_modsbatch",
937         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve.staff",
938         notes           => <<"  NOTES");
939         Returns the mvr associated with a given metarecod. If none exists, 
940         it is created.
941         NOTES
942
943 sub biblio_mrid_to_modsbatch {
944         my( $self, $client, $mrid, $args) = @_;
945
946         warn "Grabbing mvr for $mrid\n";
947
948         my ($mr, $evt) = _grab_metarecord($mrid);
949         return $evt unless $mr;
950
951         my $mvr = biblio_mrid_check_mvr($self, $client, $mr);
952         $mvr = biblio_mrid_make_modsbatch( $self, $client, $mr ) unless $mvr;
953
954         return $mvr unless ref($args);  
955
956         # Here we find the lead record appropriate for the given filters 
957         # and use that for the title and author of the metarecord
958         my $format      = $$args{format};
959         my $org         = $$args{org};
960         my $depth       = $$args{depth};
961
962         return $mvr unless $format or $org or $depth;
963
964         my $method = "open-ils.storage.ordered.metabib.metarecord.records";
965         $method = "$method.staff" if $self->api_name =~ /staff/o; 
966
967         my $rec = $U->storagereq($method, $format, $org, $depth, 1);
968
969         if( my $mods = $U->record_to_mvr($rec) ) {
970
971                 $mvr->title($mods->title);
972                 $mvr->title($mods->author);
973                 $logger->debug("mods_slim updating title and ".
974                         "author in mvr with ".$mods->title." : ".$mods->author);
975         }
976
977         return $mvr;
978 }
979
980 # converts a metarecord to an mvr
981 sub _mr_to_mvr {
982         my $mr = shift;
983         my $perl = OpenSRF::Utils::JSON->JSON2perl($mr->mods());
984         return Fieldmapper::metabib::virtual_record->new($perl);
985 }
986
987 # checks to see if a metarecord has mods, if so returns true;
988
989 __PACKAGE__->register_method(
990         method  => "biblio_mrid_check_mvr",
991         api_name        => "open-ils.search.biblio.metarecord.mods_slim.check",
992         notes           => <<"  NOTES");
993         Takes a metarecord ID or a metarecord object and returns true
994         if the metarecord already has an mvr associated with it.
995         NOTES
996
997 sub biblio_mrid_check_mvr {
998         my( $self, $client, $mrid ) = @_;
999         my $mr; 
1000
1001         my $evt;
1002         if(ref($mrid)) { $mr = $mrid; } 
1003         else { ($mr, $evt) = _grab_metarecord($mrid); }
1004         return $evt if $evt;
1005
1006         warn "Checking mvr for mr " . $mr->id . "\n";
1007
1008         return _mr_to_mvr($mr) if $mr->mods();
1009         return undef;
1010 }
1011
1012 sub _grab_metarecord {
1013         my $mrid = shift;
1014         #my $e = OpenILS::Utils::Editor->new;
1015         my $e = new_editor();
1016         my $mr = $e->retrieve_metabib_metarecord($mrid) or return ( undef, $e->event );
1017         return ($mr);
1018 }
1019
1020
1021 __PACKAGE__->register_method(
1022         method  => "biblio_mrid_make_modsbatch",
1023         api_name        => "open-ils.search.biblio.metarecord.mods_slim.create",
1024         notes           => <<"  NOTES");
1025         Takes either a metarecord ID or a metarecord object.
1026         Forces the creations of an mvr for the given metarecord.
1027         The created mvr is returned.
1028         NOTES
1029
1030 sub biblio_mrid_make_modsbatch {
1031         my( $self, $client, $mrid ) = @_;
1032
1033         #my $e = OpenILS::Utils::Editor->new;
1034         my $e = new_editor();
1035
1036         my $mr;
1037         if( ref($mrid) ) {
1038                 $mr = $mrid;
1039                 $mrid = $mr->id;
1040         } else {
1041                 $mr = $e->retrieve_metabib_metarecord($mrid) 
1042                         or return $e->event;
1043         }
1044
1045         my $masterid = $mr->master_record;
1046         $logger->info("creating new mods batch for metarecord=$mrid, master record=$masterid");
1047
1048         my $ids = $U->storagereq(
1049                 'open-ils.storage.ordered.metabib.metarecord.records.staff.atomic', $mrid);
1050         return undef unless @$ids;
1051
1052         my $master = $e->retrieve_biblio_record_entry($masterid)
1053                 or return $e->event;
1054
1055         # start the mods batch
1056         my $u = OpenILS::Utils::ModsParser->new();
1057         $u->start_mods_batch( $master->marc );
1058
1059         # grab all of the sub-records and shove them into the batch
1060         my @ids = grep { $_ ne $masterid } @$ids;
1061         #my $subrecs = (@ids) ? $e->batch_retrieve_biblio_record_entry(\@ids) : [];
1062
1063         my $subrecs = [];
1064         if(@$ids) {
1065                 for my $i (@$ids) {
1066                         my $r = $e->retrieve_biblio_record_entry($i);
1067                         push( @$subrecs, $r ) if $r;
1068                 }
1069         }
1070
1071         for(@$subrecs) {
1072                 $logger->debug("adding record ".$_->id." to mods batch for metarecord=$mrid");
1073                 $u->push_mods_batch( $_->marc ) if $_->marc;
1074         }
1075
1076
1077         # finish up and send to the client
1078         my $mods = $u->finish_mods_batch();
1079         $mods->doc_id($mrid);
1080         $client->respond_complete($mods);
1081
1082
1083         # now update the mods string in the db
1084         my $string = OpenSRF::Utils::JSON->perl2JSON($mods->decast);
1085         $mr->mods($string);
1086
1087         #$e = OpenILS::Utils::Editor->new(xact => 1);
1088         $e = new_editor(xact => 1);
1089         $e->update_metabib_metarecord($mr) 
1090                 or $logger->error("Error setting mods text on metarecord $mrid : " . Dumper($e->event));
1091         $e->finish;
1092
1093         return undef;
1094 }
1095
1096
1097
1098
1099 # converts a mr id into a list of record ids
1100
1101 __PACKAGE__->register_method(
1102         method  => "biblio_mrid_to_record_ids",
1103         api_name        => "open-ils.search.biblio.metarecord_to_records",
1104 );
1105
1106 __PACKAGE__->register_method(
1107         method  => "biblio_mrid_to_record_ids",
1108         api_name        => "open-ils.search.biblio.metarecord_to_records.staff",
1109 );
1110
1111 sub biblio_mrid_to_record_ids {
1112         my( $self, $client, $mrid, $args ) = @_;
1113
1114         my $format      = $$args{format};
1115         my $org         = $$args{org};
1116         my $depth       = $$args{depth};
1117
1118         my $method = "open-ils.storage.ordered.metabib.metarecord.records.atomic";
1119         $method =~ s/atomic/staff\.atomic/o if $self->api_name =~ /staff/o; 
1120         my $recs = $U->storagereq($method, $mrid, $format, $org, $depth);
1121
1122         return { count => scalar(@$recs), ids => $recs };
1123 }
1124
1125
1126 __PACKAGE__->register_method(
1127         method  => "biblio_record_to_marc_html",
1128         api_name        => "open-ils.search.biblio.record.html" );
1129
1130 my $parser              = XML::LibXML->new();
1131 my $xslt                        = XML::LibXSLT->new();
1132 my $marc_sheet;
1133
1134 my $settings_client = OpenSRF::Utils::SettingsClient->new();
1135 sub biblio_record_to_marc_html {
1136         my( $self, $client, $recordid ) = @_;
1137
1138         if( !$marc_sheet ) {
1139                 my $dir = $settings_client->config_value( "dirs", "xsl" );
1140                 my $xsl = $settings_client->config_value(
1141                         "apps", "open-ils.search", "app_settings", "marc_html_xsl" );
1142
1143                 $xsl = $parser->parse_file("$dir/$xsl");
1144                 $marc_sheet = $xslt->parse_stylesheet( $xsl );
1145         }
1146
1147
1148         my $record = $apputils->simple_scalar_request(
1149                 "open-ils.cstore", 
1150                 "open-ils.cstore.direct.biblio.record_entry.retrieve",
1151                 $recordid );
1152
1153         my $xmldoc = $parser->parse_string($record->marc);
1154         my $html = $marc_sheet->transform($xmldoc);
1155         $html = $html->toString();
1156         return $html;
1157
1158 }
1159
1160
1161 =head duplicate
1162 __PACKAGE__->register_method(
1163         method  => "retrieve_all_copy_locations",
1164         api_name        => "open-ils.search.config.copy_location.retrieve.all" );
1165
1166 my $shelving_locations;
1167 sub retrieve_all_copy_locations {
1168         my( $self, $client ) = @_;
1169         if(!$shelving_locations) {
1170                 $shelving_locations = $apputils->simple_scalar_request(
1171                         "open-ils.cstore", 
1172                         "open-ils.cstore.direct.asset.copy_location.search.atomic",
1173                         { id => { "!=" => undef } }
1174                 );
1175         }
1176         return $shelving_locations;
1177 }
1178 =cut
1179
1180
1181
1182 __PACKAGE__->register_method(
1183         method  => "retrieve_all_copy_statuses",
1184         api_name        => "open-ils.search.config.copy_status.retrieve.all" );
1185
1186 my $copy_statuses;
1187 sub retrieve_all_copy_statuses {
1188         my( $self, $client ) = @_;
1189         return $copy_statuses if $copy_statuses;
1190         return $copy_statuses = 
1191                 new_editor()->retrieve_all_config_copy_status();
1192 }
1193
1194
1195 __PACKAGE__->register_method(
1196         method  => "copy_counts_per_org",
1197         api_name        => "open-ils.search.biblio.copy_counts.retrieve");
1198
1199 __PACKAGE__->register_method(
1200         method  => "copy_counts_per_org",
1201         api_name        => "open-ils.search.biblio.copy_counts.retrieve.staff");
1202
1203 sub copy_counts_per_org {
1204         my( $self, $client, $record_id ) = @_;
1205
1206         warn "Retreiveing copy copy counts for record $record_id and method " . $self->api_name . "\n";
1207
1208         my $method = "open-ils.storage.biblio.record_entry.global_copy_count.atomic";
1209         if($self->api_name =~ /staff/) { $method =~ s/atomic/staff\.atomic/; }
1210
1211         my $counts = $apputils->simple_scalar_request(
1212                 "open-ils.storage", $method, $record_id );
1213
1214         $counts = [ sort {$a->[0] <=> $b->[0]} @$counts ];
1215         return $counts;
1216 }
1217
1218
1219 __PACKAGE__->register_method(
1220         method          => "copy_count_summary",
1221         api_name        => "open-ils.search.biblio.copy_counts.summary.retrieve",
1222         notes           => <<"  NOTES");
1223         returns an array of these:
1224                 [ org_id, callnumber_label, <status1_count>, <status2_cout>,...]
1225                 where statusx is a copy status name.  the statuses are sorted
1226                 by id.
1227         NOTES
1228
1229 sub copy_count_summary {
1230         my( $self, $client, $rid, $org, $depth ) = @_;
1231         $org ||= 1;
1232         $depth ||= 0;
1233     my $data = $U->storagereq(
1234                 'open-ils.storage.biblio.record_entry.status_copy_count.atomic', $rid, $org, $depth );
1235
1236     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1237 }
1238
1239
1240
1241 =head
1242 __PACKAGE__->register_method(
1243         method          => "multiclass_search",
1244         api_name        => "open-ils.search.biblio.multiclass",
1245         notes           => <<"  NOTES");
1246                 Performs a multiclass search
1247                 PARAMS( searchBlob, org_unit, format, limit ) 
1248                 where searchBlob is defined like this:
1249                         { 
1250                                 "title" : { "term" : "water" }, 
1251                                 "author" : { "term" : "smith" }, 
1252                                 ... 
1253                         }
1254         NOTES
1255
1256 __PACKAGE__->register_method(
1257         method          => "multiclass_search",
1258         api_name        => "open-ils.search.biblio.multiclass.staff",
1259         notes           => "see open-ils.search.biblio.multiclass" );
1260
1261 sub multiclass_search {
1262         my( $self, $client, $searchBlob, $orgid, $format, $limit ) = @_;
1263
1264         $logger->debug("Performing multiclass search with org => $orgid, " .
1265                 "format => $format, limit => $limit, and search blob " . Dumper($searchBlob));
1266
1267         my $meth = 'open-ils.storage.metabib.post_filter.multiclass.search_fts.metarecord.atomic';
1268         if($self->api_name =~ /staff/) { $meth =~ s/metarecord\.atomic/metarecord.staff.atomic/; }
1269
1270
1271         my $records = $apputils->simplereq(
1272                 'open-ils.storage', $meth, 
1273                  org_unit => $orgid, searches => $searchBlob, format => $format, limit => $limit );
1274
1275         my $count = 0;
1276         my $recs = [];
1277
1278         if( ref($records) and $records->[0] and 
1279                 defined($records->[0]->[3])) { $count = $records->[0]->[3];}
1280
1281         for my $r (@$records) { push( @$recs, $r ) if ($r and $r->[0]); }
1282
1283         # records has the form: [ mrid, rank, singleRecord / 0, hitCount ];
1284         return { ids => $recs, count => $count };
1285 }
1286 =cut
1287
1288
1289 =head comment-1
1290 __PACKAGE__->register_method(
1291         method          => "multiclass_search",
1292         api_name                => "open-ils.search.biblio.multiclass",
1293         signature       => q/
1294                 Performs a multiclass search
1295                 @param args A names hash of arguments:
1296                         org_unit : The org to focus the search on
1297                         depth           : The search depth
1298                         format  : Item format
1299                         limit           : Return limit
1300                         offset  : Search offset
1301                         searches : A named hash of searches which has the following format:
1302                                 { 
1303                                         "title" : { "term" : "water" }, 
1304                                         "author" : { "term" : "smith" }, 
1305                                         ... 
1306                                 }
1307                 @return { ids : <array of ids>, count : hitcount }
1308         /
1309 );
1310
1311 __PACKAGE__->register_method(
1312         method          => "multiclass_search",
1313         api_name                => "open-ils.search.biblio.multiclass.staff",
1314         notes           => q/@see open-ils.search.biblio.multiclass/ );
1315
1316 sub multiclass_search {
1317         my( $self, $client, $args ) = @_;
1318
1319         $logger->debug("Performing multiclass search with args:\n" . Dumper($args));
1320         my $meth = 'open-ils.storage.metabib.post_filter.multiclass.search_fts.metarecord.atomic';
1321         if($self->api_name =~ /staff/) { $meth =~ s/metarecord\.atomic/metarecord.staff.atomic/; }
1322
1323         my $records = $apputils->simplereq( 'open-ils.storage', $meth, %$args );
1324
1325         my $count = 0;
1326         my $recs = [];
1327
1328         if( ref($records) and $records->[0] and 
1329                 defined($records->[0]->[3])) { $count = $records->[0]->[3];}
1330
1331         for my $r (@$records) { push( @$recs, $r ) if ($r and $r->[0]); }
1332
1333         return { ids => $recs, count => $count };
1334 }
1335
1336 =cut
1337
1338
1339
1340 __PACKAGE__->register_method(
1341         method          => "marc_search",
1342         api_name        => "open-ils.search.biblio.marc.staff");
1343
1344 __PACKAGE__->register_method(
1345         method          => "marc_search",
1346         api_name        => "open-ils.search.biblio.marc",
1347         notes           => <<"  NOTES");
1348                 Example:
1349                 open-ils.storage.biblio.full_rec.multi_search.atomic 
1350                 { "searches": [{"term":"harry","restrict": [{"tag":245,"subfield":"a"}]}], "org_unit": 1,
1351         "limit":5,"sort":"author","item_type":"g"}
1352         NOTES
1353
1354 sub marc_search {
1355         my( $self, $conn, $args, $limit, $offset ) = @_;
1356
1357         my $method = 'open-ils.storage.biblio.full_rec.multi_search';
1358         $method .= ".staff" if $self->api_name =~ /staff/;
1359         $method .= ".atomic";
1360
1361         $limit ||= 10;
1362         $offset ||= 0;
1363
1364         my @search;
1365         push( @search, ($_ => $$args{$_}) ) for (sort keys %$args);
1366         my $ckey = $pfx . md5_hex($method . OpenSRF::Utils::JSON->perl2JSON(\@search));
1367
1368         my $recs = search_cache($ckey, $offset, $limit);
1369
1370         if(!$recs) {
1371                 $recs = $U->storagereq($method, %$args) || [];
1372                 if( $recs ) {
1373                         put_cache($ckey, scalar(@$recs), $recs);
1374                         $recs = [ @$recs[$offset..($offset + ($limit - 1))] ];
1375                 } else {
1376                         $recs = [];
1377                 }
1378         }
1379
1380         my $count = 0;
1381         $count = $recs->[0]->[2] if $recs->[0] and $recs->[0]->[2];
1382         my @recs = map { $_->[0] } @$recs;
1383
1384         return { ids => \@recs, count => $count };
1385 }
1386
1387
1388 __PACKAGE__->register_method(
1389         method  => "biblio_search_isbn",
1390         api_name        => "open-ils.search.biblio.isbn",
1391 );
1392
1393 sub biblio_search_isbn { 
1394         my( $self, $client, $isbn ) = @_;
1395         $logger->debug("Searching ISBN $isbn");
1396         my $e = new_editor();
1397         my $recs = $U->storagereq(
1398                 'open-ils.storage.id_list.biblio.record_entry.search.isbn.atomic', $isbn );
1399         return { ids => $recs, count => scalar(@$recs) };
1400 }
1401
1402
1403 __PACKAGE__->register_method(
1404         method  => "biblio_search_issn",
1405         api_name        => "open-ils.search.biblio.issn",
1406 );
1407
1408 sub biblio_search_issn { 
1409         my( $self, $client, $issn ) = @_;
1410         $logger->debug("Searching ISSN $issn");
1411         my $e = new_editor();
1412         my $recs = $U->storagereq(
1413                 'open-ils.storage.id_list.biblio.record_entry.search.issn.atomic', $issn );
1414         return { ids => $recs, count => scalar(@$recs) };
1415 }
1416
1417
1418
1419
1420 __PACKAGE__->register_method(
1421         method  => "fetch_mods_by_copy",
1422         api_name        => "open-ils.search.biblio.mods_from_copy",
1423 );
1424
1425 sub fetch_mods_by_copy {
1426         my( $self, $client, $copyid ) = @_;
1427         my ($record, $evt) = $apputils->fetch_record_by_copy( $copyid );
1428         return $evt if $evt;
1429         return OpenILS::Event->new('ITEM_NOT_CATALOGED') unless $record->marc;
1430         return $apputils->record_to_mvr($record);
1431 }
1432
1433
1434
1435 # -------------------------------------------------------------------------------------
1436
1437 __PACKAGE__->register_method(
1438         method  => "cn_browse",
1439         api_name        => "open-ils.search.callnumber.browse.target",
1440         notes           => "Starts a callnumber browse"
1441         );
1442
1443 __PACKAGE__->register_method(
1444         method  => "cn_browse",
1445         api_name        => "open-ils.search.callnumber.browse.page_up",
1446         notes           => "Returns the previous page of callnumbers", 
1447         );
1448
1449 __PACKAGE__->register_method(
1450         method  => "cn_browse",
1451         api_name        => "open-ils.search.callnumber.browse.page_down",
1452         notes           => "Returns the next page of callnumbers", 
1453         );
1454
1455
1456 # RETURNS array of arrays like so: label, owning_lib, record, id
1457 sub cn_browse {
1458         my( $self, $client, @params ) = @_;
1459         my $method;
1460
1461         $method = 'open-ils.storage.asset.call_number.browse.target.atomic' 
1462                 if( $self->api_name =~ /target/ );
1463         $method = 'open-ils.storage.asset.call_number.browse.page_up.atomic'
1464                 if( $self->api_name =~ /page_up/ );
1465         $method = 'open-ils.storage.asset.call_number.browse.page_down.atomic'
1466                 if( $self->api_name =~ /page_down/ );
1467
1468         return $apputils->simplereq( 'open-ils.storage', $method, @params );
1469 }
1470 # -------------------------------------------------------------------------------------
1471
1472 __PACKAGE__->register_method(
1473         method => "fetch_cn",
1474     authoritative => 1,
1475         api_name => "open-ils.search.callnumber.retrieve",
1476         notes           => "retrieves a callnumber based on ID",
1477         );
1478
1479 sub fetch_cn {
1480         my( $self, $client, $id ) = @_;
1481         my( $cn, $evt ) = $apputils->fetch_callnumber( $id );
1482         return $evt if $evt;
1483         return $cn;
1484 }
1485
1486 __PACKAGE__->register_method (
1487         method          => "fetch_copy_by_cn",
1488         api_name                => 'open-ils.search.copies_by_call_number.retrieve',
1489         signature       => q/
1490                 Returns an array of copy id's by callnumber id
1491                 @param cnid The callnumber id
1492                 @return An array of copy ids
1493         /
1494 );
1495
1496 sub fetch_copy_by_cn {
1497         my( $self, $conn, $cnid ) = @_;
1498         return $U->cstorereq(
1499                 'open-ils.cstore.direct.asset.copy.id_list.atomic', 
1500                 { call_number => $cnid, deleted => 'f' } );
1501 }
1502
1503 __PACKAGE__->register_method (
1504         method          => 'fetch_cn_by_info',
1505         api_name                => 'open-ils.search.call_number.retrieve_by_info',
1506         signature       => q/
1507                 @param label The callnumber label
1508                 @param record The record the cn is attached to
1509                 @param org The owning library of the cn
1510                 @return The callnumber object
1511         /
1512 );
1513
1514
1515 sub fetch_cn_by_info {
1516         my( $self, $conn, $label, $record, $org ) = @_;
1517         return $U->cstorereq(
1518                 'open-ils.cstore.direct.asset.call_number.search',
1519                 { label => $label, record => $record, owning_lib => $org, deleted => 'f' });
1520 }
1521
1522
1523                 
1524
1525
1526 __PACKAGE__->register_method (
1527         method => 'bib_extras',
1528         api_name => 'open-ils.search.biblio.lit_form_map.retrieve.all');
1529 __PACKAGE__->register_method (
1530         method => 'bib_extras',
1531         api_name => 'open-ils.search.biblio.item_form_map.retrieve.all');
1532 __PACKAGE__->register_method (
1533         method => 'bib_extras',
1534         api_name => 'open-ils.search.biblio.item_type_map.retrieve.all');
1535 __PACKAGE__->register_method (
1536         method => 'bib_extras',
1537         api_name => 'open-ils.search.biblio.audience_map.retrieve.all');
1538
1539 sub bib_extras {
1540         my $self = shift;
1541
1542         my $e = new_editor();
1543
1544         return $e->retrieve_all_config_lit_form_map()
1545                 if( $self->api_name =~ /lit_form/ );
1546
1547         return $e->retrieve_all_config_item_form_map()
1548                 if( $self->api_name =~ /item_form_map/ );
1549
1550         return $e->retrieve_all_config_item_type_map()
1551                 if( $self->api_name =~ /item_type_map/ );
1552
1553         return $e->retrieve_all_config_audience_map()
1554                 if( $self->api_name =~ /audience_map/ );
1555
1556         return [];
1557 }
1558
1559
1560
1561 __PACKAGE__->register_method(
1562         method  => 'fetch_slim_record',
1563         api_name        => 'open-ils.search.biblio.record_entry.slim.retrieve',
1564         signature=> q/
1565                 Returns a biblio.record_entry without the attached marcxml
1566         /
1567 );
1568
1569 sub fetch_slim_record {
1570         my( $self, $conn, $ids ) = @_;
1571
1572         #my $editor = OpenILS::Utils::Editor->new;
1573         my $editor = new_editor();
1574         my @res;
1575         for( @$ids ) {
1576                 return $editor->event unless
1577                         my $r = $editor->retrieve_biblio_record_entry($_);
1578                 $r->clear_marc;
1579                 push(@res, $r);
1580         }
1581         return \@res;
1582 }
1583
1584
1585
1586 __PACKAGE__->register_method(
1587         method => 'rec_to_mr_rec_descriptors',
1588         api_name        => 'open-ils.search.metabib.record_to_descriptors',
1589         signature       => q/
1590                 specialized method...
1591                 Given a biblio record id or a metarecord id, 
1592                 this returns a list of metabib.record_descriptor
1593                 objects that live within the same metarecord
1594                 @param args Object of args including:
1595         /
1596 );
1597
1598 sub rec_to_mr_rec_descriptors {
1599         my( $self, $conn, $args ) = @_;
1600
1601         my $rec = $$args{record};
1602         my $mrec        = $$args{metarecord};
1603         my $item_forms = $$args{item_forms};
1604         my $item_types  = $$args{item_types};
1605         my $item_lang   = $$args{item_lang};
1606
1607         my $e = new_editor();
1608         my $recs;
1609
1610         if( !$mrec ) {
1611                 my $map = $e->search_metabib_metarecord_source_map({source => $rec});
1612                 return $e->event unless @$map;
1613                 $mrec = $$map[0]->metarecord;
1614         }
1615
1616         $recs = $e->search_metabib_metarecord_source_map({metarecord => $mrec});
1617         return $e->event unless @$recs;
1618
1619         my @recs = map { $_->source } @$recs;
1620         my $search = { record => \@recs };
1621         $search->{item_form} = $item_forms if $item_forms and @$item_forms;
1622         $search->{item_type} = $item_types if $item_types and @$item_types;
1623         $search->{item_lang} = $item_lang if $item_lang;
1624
1625         my $desc = $e->search_metabib_record_descriptor($search);
1626
1627         return { metarecord => $mrec, descriptors => $desc };
1628 }
1629
1630
1631
1632
1633 __PACKAGE__->register_method(
1634         method => 'copies_created_on',  
1635 );
1636
1637
1638 sub copies_created_on {
1639         my( $self, $conn, $auth, $org, $date ) = @_;
1640         my $e = new_editor(authtoken=>$auth);
1641         return $e->event unless $e->checkauth;
1642 }
1643
1644
1645 __PACKAGE__->register_method(
1646         method => 'fetch_age_protect',
1647         api_name => 'open-ils.search.copy.age_protect.retrieve.all',
1648 );
1649
1650 sub fetch_age_protect {
1651         return new_editor()->retrieve_all_config_rule_age_hold_protect();
1652 }
1653
1654
1655 __PACKAGE__->register_method(
1656         method => 'copies_by_cn_label',
1657         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label',
1658 );
1659
1660 __PACKAGE__->register_method(
1661         method => 'copies_by_cn_label',
1662         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label.staff',
1663 );
1664
1665 sub copies_by_cn_label {
1666         my( $self, $conn, $record, $label, $circ_lib ) = @_;
1667         my $e = new_editor();
1668         my $cns = $e->search_asset_call_number({record => $record, label => $label, deleted => 'f'}, {idlist=>1});
1669         return [] unless @$cns;
1670
1671         # show all non-deleted copies in the staff client ...
1672         if ($self->api_name =~ /staff$/o) {
1673                 return $e->search_asset_copy({call_number => $cns, circ_lib => $circ_lib, deleted => 'f'}, {idlist=>1});
1674         }
1675
1676         # ... otherwise, grab the copies ...
1677         my $copies = $e->search_asset_copy(
1678                 [ {call_number => $cns, circ_lib => $circ_lib, deleted => 'f', opac_visible => 't'},
1679                   {flesh => 1, flesh_fields => { acp => [ qw/location status/] } }
1680                 ]
1681         );
1682
1683         # ... and test for location and status visibility
1684         return [ map { ($U->is_true($_->location->opac_visible) && $U->is_true($_->status->holdable)) ? ($_->id) : () } @$copies ];
1685 }
1686
1687
1688
1689 1;
1690
1691