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