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