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