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