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