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