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