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