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