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