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