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