]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Biblio.pm
ac2faf9196704984471e6844a7fa7c03c74f6159
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Search / Biblio.pm
1 package OpenILS::Application::Search::Biblio;
2 use base qw/OpenILS::Application/;
3 use strict; use warnings;
4
5
6 use OpenSRF::Utils::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 use Encode;
13
14 use OpenSRF::Utils::Logger qw/:logger/;
15
16
17 use OpenSRF::Utils::JSON;
18
19 use Time::HiRes qw(time);
20 use OpenSRF::EX qw(:try);
21 use Digest::MD5 qw(md5_hex);
22
23 use XML::LibXML;
24 use XML::LibXSLT;
25
26 use Data::Dumper;
27 $Data::Dumper::Indent = 0;
28
29 use OpenILS::Const qw/:const/;
30
31 use OpenILS::Application::AppUtils;
32 my $apputils = "OpenILS::Application::AppUtils";
33 my $U = $apputils;
34
35 my $pfx = "open-ils.search_";
36
37 my $cache;
38 my $cache_timeout;
39 my $superpage_size;
40 my $max_superpages;
41
42 sub initialize {
43         $cache = OpenSRF::Utils::Cache->new('global');
44         my $sclient = OpenSRF::Utils::SettingsClient->new();
45         $cache_timeout = $sclient->config_value(
46                         "apps", "open-ils.search", "app_settings", "cache_timeout" ) || 300;
47
48         $superpage_size = $sclient->config_value(
49                         "apps", "open-ils.search", "app_settings", "superpage_size" ) || 500;
50
51         $max_superpages = $sclient->config_value(
52                         "apps", "open-ils.search", "app_settings", "max_superpages" ) || 20;
53
54         $logger->info("Search cache timeout is $cache_timeout, ".
55         " superpage_size is $superpage_size, max_superpages is $max_superpages");
56 }
57
58
59
60 # ---------------------------------------------------------------------------
61 # takes a list of record id's and turns the docs into friendly 
62 # mods structures. Creates one MODS structure for each doc id.
63 # ---------------------------------------------------------------------------
64 sub _records_to_mods {
65         my @ids = @_;
66         
67         my @results;
68         my @marcxml_objs;
69
70         my $session = OpenSRF::AppSession->create("open-ils.cstore");
71         my $request = $session->request(
72                         "open-ils.cstore.direct.biblio.record_entry.search", { id => \@ids } );
73
74         while( my $resp = $request->recv ) {
75                 my $content = $resp->content;
76                 next if $content->id == OILS_PRECAT_RECORD;
77                 my $u = OpenILS::Utils::ModsParser->new();
78                 $u->start_mods_batch( $content->marc );
79                 my $mods = $u->finish_mods_batch();
80                 $mods->doc_id($content->id());
81                 $mods->tcn($content->tcn_value);
82                 push @results, $mods;
83         }
84
85         $session->disconnect();
86         return \@results;
87 }
88
89 __PACKAGE__->register_method(
90         method  => "record_id_to_mods",
91         api_name        => "open-ils.search.biblio.record.mods.retrieve",
92         argc            => 1, 
93         note            => "Provide ID, we provide the mods"
94 );
95
96 # converts a record into a mods object with copy counts attached
97 sub record_id_to_mods {
98
99         my( $self, $client, $org_id, $id ) = @_;
100
101         my $mods_list = _records_to_mods( $id );
102         my $mods_obj = $mods_list->[0];
103         my $cmethod = $self->method_lookup(
104                         "open-ils.search.biblio.record.copy_count");
105         my ($count) = $cmethod->run($org_id, $id);
106         $mods_obj->copy_count($count);
107
108         return $mods_obj;
109 }
110
111
112
113 __PACKAGE__->register_method(
114         method  => "record_id_to_mods_slim",
115     authoritative => 1,
116         api_name        => "open-ils.search.biblio.record.mods_slim.retrieve",
117         argc            => 1, 
118         note            => "Provide ID, we provide the mods"
119 );
120
121 # converts a record into a mods object with NO copy counts attached
122 sub record_id_to_mods_slim {
123         my( $self, $client, $id ) = @_;
124         return undef unless defined $id;
125
126         if(ref($id) and ref($id) == 'ARRAY') {
127                 return _records_to_mods( @$id );
128         }
129         my $mods_list = _records_to_mods( $id );
130         my $mods_obj = $mods_list->[0];
131         return OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND') unless $mods_obj;
132         return $mods_obj;
133 }
134
135
136 # Returns the number of copies attached to a record based on org location
137 __PACKAGE__->register_method(
138         method  => "record_id_to_copy_count",
139         api_name        => "open-ils.search.biblio.record.copy_count",
140 );
141
142 __PACKAGE__->register_method(
143         method  => "record_id_to_copy_count",
144     authoritative => 1,
145         api_name        => "open-ils.search.biblio.record.copy_count.staff",
146 );
147
148 __PACKAGE__->register_method(
149         method  => "record_id_to_copy_count",
150         api_name        => "open-ils.search.biblio.metarecord.copy_count",
151 );
152
153 __PACKAGE__->register_method(
154         method  => "record_id_to_copy_count",
155         api_name        => "open-ils.search.biblio.metarecord.copy_count.staff",
156 );
157 sub record_id_to_copy_count {
158         my( $self, $client, $org_id, $record_id, $format ) = @_;
159
160         return [] unless $record_id;
161         $format = undef if (!$format or $format eq 'all');
162
163         my $method = "open-ils.storage.biblio.record_entry.copy_count.atomic";
164         my $key = "record";
165
166         if($self->api_name =~ /metarecord/) {
167                 $method = "open-ils.storage.metabib.metarecord.copy_count.atomic";
168                 $key = "metarecord";
169         }
170
171         $method =~ s/atomic/staff\.atomic/og if($self->api_name =~ /staff/ );
172
173         my $count = $U->storagereq( $method, 
174                 org_unit => $org_id, $key => $record_id, format => $format );
175
176         return [ sort { $a->{depth} <=> $b->{depth} } @$count ];
177 }
178
179
180
181
182 __PACKAGE__->register_method(
183         method  => "biblio_search_tcn",
184         api_name        => "open-ils.search.biblio.tcn",
185         argc            => 3, 
186         note            => "Retrieve a record by TCN",
187 );
188
189 sub biblio_search_tcn {
190
191         my( $self, $client, $tcn, $include_deleted ) = @_;
192
193         $tcn =~ s/.*?(\w+)\s*$/$1/o;
194
195         my $e = new_editor();
196    my $search = {tcn_value => $tcn};
197    $search->{deleted} = 'f' unless $include_deleted;
198         my $recs = $e->search_biblio_record_entry( $search, {idlist =>1} );
199         
200         return { count => scalar(@$recs), ids => $recs };
201 }
202
203
204 # --------------------------------------------------------------------------------
205
206 __PACKAGE__->register_method(
207         method  => "biblio_barcode_to_copy",
208         api_name        => "open-ils.search.asset.copy.find_by_barcode",);
209 sub biblio_barcode_to_copy { 
210         my( $self, $client, $barcode ) = @_;
211         my( $copy, $evt ) = $U->fetch_copy_by_barcode($barcode);
212         return $evt if $evt;
213         return $copy;
214 }
215
216 __PACKAGE__->register_method(
217         method  => "biblio_id_to_copy",
218         api_name        => "open-ils.search.asset.copy.batch.retrieve",);
219 sub biblio_id_to_copy { 
220         my( $self, $client, $ids ) = @_;
221         $logger->info("Fetching copies @$ids");
222         return $U->cstorereq(
223                 "open-ils.cstore.direct.asset.copy.search.atomic", { id => $ids } );
224 }
225
226
227 __PACKAGE__->register_method(
228         method  => "copy_retrieve", 
229         api_name        => "open-ils.search.asset.copy.retrieve",);
230 sub copy_retrieve {
231         my( $self, $client, $cid ) = @_;
232         my( $copy, $evt ) = $U->fetch_copy($cid);
233         return $evt if $evt;
234         return $copy;
235 }
236
237 __PACKAGE__->register_method(
238         method  => "volume_retrieve", 
239         api_name        => "open-ils.search.asset.call_number.retrieve");
240 sub volume_retrieve {
241         my( $self, $client, $vid ) = @_;
242         my $e = new_editor();
243         my $vol = $e->retrieve_asset_call_number($vid) or return $e->event;
244         return $vol;
245 }
246
247 __PACKAGE__->register_method(
248         method  => "fleshed_copy_retrieve_batch",
249     authoritative => 1,
250         api_name        => "open-ils.search.asset.copy.fleshed.batch.retrieve");
251
252 sub fleshed_copy_retrieve_batch { 
253         my( $self, $client, $ids ) = @_;
254         $logger->info("Fetching fleshed copies @$ids");
255         return $U->cstorereq(
256                 "open-ils.cstore.direct.asset.copy.search.atomic",
257                 { id => $ids },
258                 { flesh => 1, 
259                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
260                 });
261 }
262
263
264 __PACKAGE__->register_method(
265         method  => "fleshed_copy_retrieve",
266         api_name        => "open-ils.search.asset.copy.fleshed.retrieve",);
267
268 sub fleshed_copy_retrieve { 
269         my( $self, $client, $id ) = @_;
270         my( $c, $e) = $U->fetch_fleshed_copy($id);
271         return $e if $e;
272         return $c;
273 }
274
275
276
277 __PACKAGE__->register_method(
278         method => 'fleshed_by_barcode',
279         api_name        => "open-ils.search.asset.copy.fleshed2.find_by_barcode",);
280 sub fleshed_by_barcode {
281         my( $self, $conn, $barcode ) = @_;
282         my $e = new_editor();
283         my $copyid = $e->search_asset_copy(
284                 {barcode => $barcode, deleted => 'f'}, {idlist=>1})->[0]
285                 or return $e->event;
286         return fleshed_copy_retrieve2( $self, $conn, $copyid);
287 }
288
289
290 __PACKAGE__->register_method(
291         method  => "fleshed_copy_retrieve2",
292         api_name        => "open-ils.search.asset.copy.fleshed2.retrieve",);
293
294 sub fleshed_copy_retrieve2 { 
295         my( $self, $client, $id ) = @_;
296         my $e = new_editor();
297         my $copy = $e->retrieve_asset_copy(
298                 [
299                         $id,
300                         { 
301                                 flesh                           => 2,
302                                 flesh_fields    => { 
303                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect / ],
304                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
305                                 }
306                         }
307                 ]
308         ) or return $e->event;
309
310         # For backwards compatibility
311         #$copy->stat_cat_entries($copy->stat_cat_entry_copy_maps);
312
313         if( $copy->status->id == OILS_COPY_STATUS_CHECKED_OUT ) {
314                 $copy->circulations(
315                         $e->search_action_circulation( 
316                                 [       
317                                         { target_copy => $copy->id },
318                                         {
319                                                 order_by => { circ => 'xact_start desc' },
320                                                 limit => 1
321                                         }
322                                 ]
323                         )
324                 );
325         }
326
327         return $copy;
328 }
329
330
331 __PACKAGE__->register_method(
332         method => 'flesh_copy_custom',
333         api_name => 'open-ils.search.asset.copy.fleshed.custom'
334 );
335
336 sub flesh_copy_custom {
337         my( $self, $conn, $copyid, $fields ) = @_;
338         my $e = new_editor();
339         my $copy = $e->retrieve_asset_copy(
340                 [
341                         $copyid,
342                         { 
343                                 flesh                           => 1,
344                                 flesh_fields    => { 
345                                         acp => $fields,
346                                 }
347                         }
348                 ]
349         ) or return $e->event;
350         return $copy;
351 }
352
353
354
355
356
357
358 __PACKAGE__->register_method(
359         method  => "biblio_barcode_to_title",
360         api_name        => "open-ils.search.biblio.find_by_barcode",
361 );
362
363 sub biblio_barcode_to_title {
364         my( $self, $client, $barcode ) = @_;
365
366         my $title = $apputils->simple_scalar_request(
367                 "open-ils.storage",
368                 "open-ils.storage.biblio.record_entry.retrieve_by_barcode", $barcode );
369
370         return { ids => [ $title->id ], count => 1 } if $title;
371         return { count => 0 };
372 }
373
374 __PACKAGE__->register_method(
375     method => 'title_id_by_item_barcode',
376     api_name => 'open-ils.search.bib_id.by_barcode'
377 );
378
379 sub title_id_by_item_barcode {
380     my( $self, $conn, $barcode ) = @_;
381     my $e = new_editor();
382     my $copies = $e->search_asset_copy(
383         [
384             { deleted => 'f', barcode => $barcode },
385             {
386                 flesh => 2,
387                 flesh_fields => {
388                     acp => [ 'call_number' ],
389                     acn => [ 'record' ]
390                 }
391             }
392         ]
393     );
394
395     return $e->event unless @$copies;
396     return $$copies[0]->call_number->record->id;
397 }
398
399
400 __PACKAGE__->register_method(
401         method  => "biblio_copy_to_mods",
402         api_name        => "open-ils.search.biblio.copy.mods.retrieve",
403 );
404
405 # takes a copy object and returns it fleshed mods object
406 sub biblio_copy_to_mods {
407         my( $self, $client, $copy ) = @_;
408
409         my $volume = $U->cstorereq( 
410                 "open-ils.cstore.direct.asset.call_number.retrieve",
411                 $copy->call_number() );
412
413         my $mods = _records_to_mods($volume->record());
414         $mods = shift @$mods;
415         $volume->copies([$copy]);
416         push @{$mods->call_numbers()}, $volume;
417
418         return $mods;
419 }
420
421
422 __PACKAGE__->register_method(
423     api_name => 'open-ils.search.biblio.multiclass.query',
424     method => 'multiclass_query',
425     signature => q#
426         @param arghash @see open-ils.search.biblio.multiclass
427         @param query Raw human-readable query string.  
428             Recognized search keys include: 
429                 keyword/kw - search keyword(s)
430                 author/au/name - search author(s)
431                 title/ti - search title
432                 subject/su - search subject
433                 series/se - search series
434                 lang - limit by language (specifiy multiple langs with lang:l1 lang:l2 ...)
435                 site - search at specified org unit, corresponds to actor.org_unit.shortname
436                 sort - sort type (title, author, pubdate)
437                 dir - sort direction (asc, desc)
438                 available - if set to anything other than "false" or "0", limits to available items
439
440                 keyword, title, author, subject, and series support additional search 
441                 subclasses, specified with a "|". For example, "title|proper:gone with the wind" 
442                 For more, see config.metabib_field
443
444         @param docache @see open-ils.search.biblio.multiclass
445     #
446 );
447 __PACKAGE__->register_method(
448     api_name => 'open-ils.search.biblio.multiclass.query.staff',
449     method => 'multiclass_query',
450     signature => '@see open-ils.search.biblio.multiclass.query');
451 __PACKAGE__->register_method(
452     api_name => 'open-ils.search.metabib.multiclass.query',
453     method => 'multiclass_query',
454     signature => '@see open-ils.search.biblio.multiclass.query');
455 __PACKAGE__->register_method(
456     api_name => 'open-ils.search.metabib.multiclass.query.staff',
457     method => 'multiclass_query',
458     signature => '@see open-ils.search.biblio.multiclass.query');
459
460 sub multiclass_query {
461     my($self, $conn, $arghash, $query, $docache) = @_;
462
463     $logger->debug("initial search query => $query");
464     my $orig_query = $query;
465
466     $query =~ s/\+/ /go;
467     $query =~ s/'//go;
468     $query =~ s/^\s+//go;
469
470     # convert convenience classes (e.g. kw for keyword) to the full class name
471     $query =~ s/kw(:|\|)/keyword$1/go;
472     $query =~ s/ti(:|\|)/title$1/go;
473     $query =~ s/au(:|\|)/author$1/go;
474     $query =~ s/su(:|\|)/subject$1/go;
475     $query =~ s/se(:|\|)/series$1/go;
476     $query =~ s/name(:|\|)/author$1/og;
477
478     $logger->debug("cleansed query string => $query");
479     my $search = $arghash->{searches} = {};
480
481     while ($query =~ s/((?:keyword(?:\|\w+)?|title(?:\|\w+)?|author(?:\|\w+)?|subject(?:\|\w+)?|series(?:\|\w+)?|site|dir|sort|lang|available):[^:]+)$//so) {
482         my($type, $value) = split(':', $1);
483         next unless $type and $value;
484
485         $value =~ s/^\s*//og;
486         $value =~ s/\s*$//og;
487         $type = 'sort_dir' if $type eq 'dir';
488
489         if($type eq 'site') {
490             # 'site' is the org shortname.  when using this, we also want 
491             # to search at the requested org's depth
492             my $e = new_editor();
493             if(my $org = $e->search_actor_org_unit({shortname => $value})->[0]) {
494                 $arghash->{org_unit} = $org->id if $org;
495                 $arghash->{depth} = $e->retrieve_actor_org_unit_type($org->ou_type)->depth;
496             } else {
497                 $logger->warn("'site:' query used on invalid org shortname: $value ... ignoring");
498             }
499
500         } elsif($type eq 'available') {
501             # limit to available
502             $arghash->{available} = 1 unless $value eq 'false' or $value eq '0';
503
504         } elsif($type eq 'lang') {
505             # collect languages into an array of languages
506             $arghash->{language} = [] unless $arghash->{language};
507             push(@{$arghash->{language}}, $value);
508
509         } elsif($type =~ /^sort/o) {
510             # sort and sort_dir modifiers
511             $arghash->{$type} = $value;
512
513         } else {
514             # append the search term to the term under construction
515             $search->{$type} =  {} unless $search->{$type};
516             $search->{$type}->{term} =  
517                 ($search->{$type}->{term}) ? $search->{$type}->{term} . " $value" : $value;
518         }
519     }
520
521     if($query) {
522         # This is the front part of the string before any special tokens were parsed. 
523         # Add this data to the default search class
524         my $type = $arghash->{default_class} || 'keyword';
525         $search->{$type} =  {} unless $search->{$type};
526         $search->{$type}->{term} =
527             ($search->{$type}->{term}) ? $search->{$type}->{term} . " $query" : $query;
528     }
529
530     # capture the original limit because the search method alters the limit internally
531     my $ol = $arghash->{limit};
532
533         my $sclient = OpenSRF::Utils::SettingsClient->new;
534
535     (my $method = $self->api_name) =~ s/\.query//o;
536
537     $method =~ s/multiclass/multiclass.staged/
538         if $sclient->config_value(apps => 'open-ils.search',
539             app_settings => 'use_staged_search') =~ /true/i;
540
541
542         $method = $self->method_lookup($method);
543     my ($data) = $method->run($arghash, $docache);
544
545     $arghash->{limit} = $ol if $ol;
546     $data->{compiled_search} = $arghash;
547     $data->{query} = $orig_query;
548
549     $logger->info("compiled search is " . OpenSRF::Utils::JSON->perl2JSON($arghash));
550
551     return $data;
552 }
553
554 __PACKAGE__->register_method(
555         method          => 'cat_search_z_style_wrapper',
556         api_name        => 'open-ils.search.biblio.zstyle',
557         stream          => 1,
558         signature       => q/@see open-ils.search.biblio.multiclass/);
559
560 sub cat_search_z_style_wrapper {
561         my $self = shift;
562         my $client = shift;
563         my $authtoken = shift;
564         my $args = shift;
565
566         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
567
568         my $ou = $cstore->request(
569                 'open-ils.cstore.direct.actor.org_unit.search',
570                 { parent_ou => undef }
571         )->gather(1);
572
573         my $result = { service => 'native-evergreen-catalog', records => [] };
574         my $searchhash = { limit => $$args{limit}, offset => $$args{offset}, org_unit => $ou->id };
575
576         $$searchhash{searches}{title}{term} = $$args{search}{title} if $$args{search}{title};
577         $$searchhash{searches}{author}{term} = $$args{search}{author} if $$args{search}{author};
578         $$searchhash{searches}{subject}{term} = $$args{search}{subject} if $$args{search}{subject};
579         $$searchhash{searches}{keyword}{term} = $$args{search}{keyword} if $$args{search}{keyword};
580
581         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{tcn} if $$args{search}{tcn};
582         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{isbn} if $$args{search}{isbn};
583         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{issn} if $$args{search}{issn};
584         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{publisher} if $$args{search}{publisher};
585         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{pubdate} if $$args{search}{pubdate};
586         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{item_type} if $$args{search}{item_type};
587
588         my $list = the_quest_for_knowledge( $self, $client, $searchhash );
589
590         if ($list->{count} > 0) {
591                 $result->{count} = $list->{count};
592
593                 my $records = $cstore->request(
594                         'open-ils.cstore.direct.biblio.record_entry.search.atomic',
595                         { id => [ map { ( $_->[0] ) } @{$list->{ids}} ] }
596                 )->gather(1);
597
598                 for my $rec ( @$records ) {
599                         
600                         my $u = OpenILS::Utils::ModsParser->new();
601                         $u->start_mods_batch( $rec->marc );
602                         my $mods = $u->finish_mods_batch();
603
604                         push @{ $result->{records} }, { mvr => $mods, marcxml => $rec->marc, bibid => $rec->id };
605
606                 }
607
608         }
609
610     $cstore->disconnect();
611         return $result;
612 }
613
614 # ----------------------------------------------------------------------------
615 # These are the main OPAC search methods
616 # ----------------------------------------------------------------------------
617
618 __PACKAGE__->register_method(
619         method          => 'the_quest_for_knowledge',
620         api_name                => 'open-ils.search.biblio.multiclass',
621         signature       => q/
622                 Performs a multi class bilbli or metabib search
623                 @param searchhash A search object layed out like so:
624                         searches : { "$class" : "$value", ...}
625                         org_unit : The org id to focus the search at
626                         depth           : The org depth
627                         limit           : The search limit
628                         offset  : The search offset
629                         format  : The MARC format
630                         sort            : What field to sort the results on [ author | title | pubdate ]
631                         sort_dir        : What direction do we sort? [ asc | desc ]
632                 @return An object of the form 
633                         { "count" : $count, "ids" : [ [ $id, $relevancy, $total ], ...] }
634         /
635 );
636
637 __PACKAGE__->register_method(
638         method          => 'the_quest_for_knowledge',
639         api_name                => 'open-ils.search.biblio.multiclass.staff',
640         signature       => q/@see open-ils.search.biblio.multiclass/);
641 __PACKAGE__->register_method(
642         method          => 'the_quest_for_knowledge',
643         api_name                => 'open-ils.search.metabib.multiclass',
644         signature       => q/@see open-ils.search.biblio.multiclass/);
645 __PACKAGE__->register_method(
646         method          => 'the_quest_for_knowledge',
647         api_name                => 'open-ils.search.metabib.multiclass.staff',
648         signature       => q/@see open-ils.search.biblio.multiclass/);
649
650 sub the_quest_for_knowledge {
651         my( $self, $conn, $searchhash, $docache ) = @_;
652
653         return { count => 0 } unless $searchhash and
654                 ref $searchhash->{searches} eq 'HASH';
655
656         my $method = 'open-ils.storage.biblio.multiclass.search_fts';
657         my $ismeta = 0;
658         my @recs;
659
660         if($self->api_name =~ /metabib/) {
661                 $ismeta = 1;
662                 $method =~ s/biblio/metabib/o;
663         }
664
665
666         my $offset      = $searchhash->{offset} || 0;
667         my $limit       = $searchhash->{limit} || 10;
668         my $end         = $offset + $limit - 1;
669
670         # do some simple sanity checking
671         if(!$searchhash->{searches} or
672                 ( !grep { /^(?:title|author|subject|series|keyword)/ } keys %{$searchhash->{searches}} ) ) {
673                 return { count => 0 };
674         }
675
676
677         my $maxlimit = 5000;
678         $searchhash->{offset}   = 0;
679         $searchhash->{limit}            = $maxlimit;
680
681         return { count => 0 } if $offset > $maxlimit;
682
683         my @search;
684         push( @search, ($_ => $$searchhash{$_})) for (sort keys %$searchhash);
685         my $s = OpenSRF::Utils::JSON->perl2JSON(\@search);
686         my $ckey = $pfx . md5_hex($method . $s);
687
688         $logger->info("bib search for: $s");
689
690         $searchhash->{limit} -= $offset;
691
692
693     my $trim = 0;
694         my $result = ($docache) ? search_cache($ckey, $offset, $limit) : undef;
695
696         if(!$result) {
697
698                 $method .= ".staff" if($self->api_name =~ /staff/);
699                 $method .= ".atomic";
700         
701                 for (keys %$searchhash) { 
702                         delete $$searchhash{$_} 
703                                 unless defined $$searchhash{$_}; 
704                 }
705         
706                 $result = $U->storagereq( $method, %$searchhash );
707         $trim = 1;
708
709         } else { 
710                 $docache = 0; 
711         }
712
713         return {count => 0} unless ($result && $$result[0]);
714
715         @recs = @$result;
716
717         my $count = ($ismeta) ? $result->[0]->[3] : $result->[0]->[2];
718
719         if($docache) {
720                 # If we didn't get this data from the cache, put it into the cache
721                 # then return the correct offset of records
722                 $logger->debug("putting search cache $ckey\n");
723                 put_cache($ckey, $count, \@recs);
724         }
725
726     if($trim) {
727         # if we have the full set of data, trim out 
728         # the requested chunk based on limit and offset
729         my @t;
730         for ($offset..$end) {
731             last unless $recs[$_];
732             push(@t, $recs[$_]);
733         }
734         @recs = @t;
735     }
736
737         return { ids => \@recs, count => $count };
738 }
739
740
741 __PACKAGE__->register_method(
742         method          => 'staged_search',
743         api_name        => 'open-ils.search.biblio.multiclass.staged');
744 __PACKAGE__->register_method(
745         method          => 'staged_search',
746         api_name        => 'open-ils.search.biblio.multiclass.staged.staff',
747         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
748 __PACKAGE__->register_method(
749         method          => 'staged_search',
750         api_name        => 'open-ils.search.metabib.multiclass.staged',
751         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
752 __PACKAGE__->register_method(
753         method          => 'staged_search',
754         api_name        => 'open-ils.search.metabib.multiclass.staged.staff',
755         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
756
757 sub staged_search {
758         my($self, $conn, $search_hash, $docache) = @_;
759
760     my $method = ($self->api_name =~ /metabib/) ?
761         'open-ils.storage.metabib.multiclass.staged.search_fts':
762         'open-ils.storage.biblio.multiclass.staged.search_fts';
763
764     $method .= '.staff' if $self->api_name =~ /staff$/;
765     $method .= '.atomic';
766
767     my $user_offset = $search_hash->{offset} || 0; # user-specified offset
768     my $user_limit = $search_hash->{limit} || 10;
769     $user_offset = ($user_offset >= 0) ? $user_offset : 0;
770     $user_limit = ($user_limit >= 0) ? $user_limit : 10;
771
772
773     # we're grabbing results on a per-superpage basis, which means the 
774     # limit and offset should coincide with superpage boundaries
775     $search_hash->{offset} = 0;
776     $search_hash->{limit} = $superpage_size;
777
778     # force a well-known check_limit
779     $search_hash->{check_limit} = $superpage_size; 
780     # restrict total tested to superpage size * number of superpages
781     $search_hash->{core_limit} = $superpage_size * $max_superpages;
782
783     # Set the configured estimation strategy, defaults to 'inclusion'.
784         $search_hash->{estimation_strategy} = OpenSRF::Utils::SettingsClient
785         ->new
786         ->config_value(
787             apps => 'open-ils.search', app_settings => 'estimation_strategy'
788         );
789
790     # pull any existing results from the cache
791     my $key = search_cache_key($method, $search_hash);
792     my $cache_data = $cache->get_cache($key) || {};
793
794     # keep retrieving results until we find enough to 
795     # fulfill the user-specified limit and offset
796     my $all_results = [];
797     my $page; # current superpage
798     my $est_hit_count = 0;
799     my $current_page_summary = {};
800
801     for($page = 0; $page < $max_superpages; $page++) {
802
803         my $data = $cache_data->{$page};
804         my $results;
805         my $summary;
806
807         $logger->debug("staged search: analyzing superpage $page");
808
809         if($data) {
810             # this window of results is already cached
811             $logger->debug("staged search: found cached results");
812             $summary = $data->{summary};
813             $results = $data->{results};
814
815         } else {
816             # retrieve the window of results from the database
817             $logger->debug("staged search: fetching results from the database");
818             $search_hash->{skip_check} = $page * $superpage_size;
819             my $start = time;
820             $results = $U->storagereq($method, %$search_hash);
821             $logger->info("staged search: DB call took ".(time - $start)." seconds");
822             $summary = shift(@$results);
823
824             # Create backwards-compatible result structures
825             if($self->api_name =~ /biblio/) {
826                 $results = [map {[$_->{id}]} @$results];
827             } else {
828                 $results = [map {[$_->{id}, $_->{rel}, $_->{record}]} @$results];
829             }
830
831             $results = [grep {defined $_->[0]} @$results];
832             cache_staged_search_page($key, $page, $summary, $results) if $docache;
833         }
834
835         $current_page_summary = $summary;
836
837         # add the new set of results to the set under construction
838         push(@$all_results, @$results);
839
840         my $current_count = scalar(@$all_results);
841
842         $est_hit_count = $summary->{estimated_hit_count} || $summary->{visible}
843             if $page == 0;
844
845         $logger->debug("staged search: located $current_count, with estimated hits=".
846             $summary->{estimated_hit_count}." : visible=".$summary->{visible}.", checked=".$summary->{checked});
847
848         # we've found all the possible hits
849         last if $current_count == $summary->{visible}
850             and not defined $summary->{estimated_hit_count};
851
852         # we've found enough results to satisfy the requested limit/offset
853         last if $current_count >= ($user_limit + $user_offset);
854
855         # we've scanned all possible hits
856         last if $summary->{checked} < $superpage_size;
857     }
858
859     my @results = grep {defined $_} @$all_results[$user_offset..($user_offset + $user_limit - 1)];
860
861     return {
862         count => $est_hit_count,
863         core_limit => $search_hash->{core_limit},
864         superpage_size => $search_hash->{check_limit},
865         superpage_summary => $current_page_summary,
866         ids => \@results
867     };
868 }
869
870 # creates a unique token to represent the query in the cache
871 sub search_cache_key {
872     my $method = shift;
873     my $search_hash = shift;
874         my @sorted;
875     for my $key (sort keys %$search_hash) {
876             push(@sorted, ($key => $$search_hash{$key})) 
877             unless $key eq 'limit' or 
878                 $key eq 'offset' or 
879                 $key eq 'skip_check';
880     }
881         my $s = OpenSRF::Utils::JSON->perl2JSON(\@sorted);
882         return $pfx . md5_hex($method . $s);
883 }
884
885 sub cache_staged_search_page {
886     # puts this set of results into the cache
887     my($key, $page, $summary, $results) = @_;
888     my $data = $cache->get_cache($key);
889     $data ||= {};
890     $data->{$page} = {
891         summary => $summary,
892         results => $results
893     };
894
895     $logger->info("staged search: cached with key=$key, superpage=$page, estimated=".
896         $summary->{estimated_hit_count}.", visible=".$summary->{visible});
897
898     $cache->put_cache($key, $data);
899 }
900
901 sub search_cache {
902
903         my $key         = shift;
904         my $offset      = shift;
905         my $limit       = shift;
906         my $start       = $offset;
907         my $end         = $offset + $limit - 1;
908
909         $logger->debug("searching cache for $key : $start..$end\n");
910
911         return undef unless $cache;
912         my $data = $cache->get_cache($key);
913
914         return undef unless $data;
915
916         my $count = $data->[0];
917         $data = $data->[1];
918
919         return undef unless $offset < $count;
920
921         my @result;
922         for( my $i = $offset; $i <= $end; $i++ ) {
923                 last unless my $d = $$data[$i];
924                 push( @result, $d );
925         }
926
927         $logger->debug("search_cache found ".scalar(@result)." items for count=$count, start=$start, end=$end");
928
929         return \@result;
930 }
931
932
933 sub put_cache {
934         my( $key, $count, $data ) = @_;
935         return undef unless $cache;
936         $logger->debug("search_cache putting ".
937                 scalar(@$data)." items at key $key with timeout $cache_timeout");
938         $cache->put_cache($key, [ $count, $data ], $cache_timeout);
939 }
940
941
942
943
944
945
946 __PACKAGE__->register_method(
947         method  => "biblio_mrid_to_modsbatch_batch",
948         api_name        => "open-ils.search.biblio.metarecord.mods_slim.batch.retrieve");
949
950 sub biblio_mrid_to_modsbatch_batch {
951         my( $self, $client, $mrids) = @_;
952         warn "Performing mrid_to_modsbatch_batch...";
953         my @mods;
954         my $method = $self->method_lookup("open-ils.search.biblio.metarecord.mods_slim.retrieve");
955         for my $id (@$mrids) {
956                 next unless defined $id;
957                 my ($m) = $method->run($id);
958                 push @mods, $m;
959         }
960         return \@mods;
961 }
962
963
964 __PACKAGE__->register_method(
965         method  => "biblio_mrid_to_modsbatch",
966         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve",
967         notes           => <<"  NOTES");
968         Returns the mvr associated with a given metarecod. If none exists, 
969         it is created.
970         NOTES
971
972 __PACKAGE__->register_method(
973         method  => "biblio_mrid_to_modsbatch",
974         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve.staff",
975         notes           => <<"  NOTES");
976         Returns the mvr associated with a given metarecod. If none exists, 
977         it is created.
978         NOTES
979
980 sub biblio_mrid_to_modsbatch {
981         my( $self, $client, $mrid, $args) = @_;
982
983         warn "Grabbing mvr for $mrid\n";
984
985         my ($mr, $evt) = _grab_metarecord($mrid);
986         return $evt unless $mr;
987
988         my $mvr = biblio_mrid_check_mvr($self, $client, $mr);
989         $mvr = biblio_mrid_make_modsbatch( $self, $client, $mr ) unless $mvr;
990
991         return $mvr unless ref($args);  
992
993         # Here we find the lead record appropriate for the given filters 
994         # and use that for the title and author of the metarecord
995         my $format      = $$args{format};
996         my $org         = $$args{org};
997         my $depth       = $$args{depth};
998
999         return $mvr unless $format or $org or $depth;
1000
1001         my $method = "open-ils.storage.ordered.metabib.metarecord.records";
1002         $method = "$method.staff" if $self->api_name =~ /staff/o; 
1003
1004         my $rec = $U->storagereq($method, $format, $org, $depth, 1);
1005
1006         if( my $mods = $U->record_to_mvr($rec) ) {
1007
1008                 $mvr->title($mods->title);
1009                 $mvr->title($mods->author);
1010                 $logger->debug("mods_slim updating title and ".
1011                         "author in mvr with ".$mods->title." : ".$mods->author);
1012         }
1013
1014         return $mvr;
1015 }
1016
1017 # converts a metarecord to an mvr
1018 sub _mr_to_mvr {
1019         my $mr = shift;
1020         my $perl = OpenSRF::Utils::JSON->JSON2perl($mr->mods());
1021         return Fieldmapper::metabib::virtual_record->new($perl);
1022 }
1023
1024 # checks to see if a metarecord has mods, if so returns true;
1025
1026 __PACKAGE__->register_method(
1027         method  => "biblio_mrid_check_mvr",
1028         api_name        => "open-ils.search.biblio.metarecord.mods_slim.check",
1029         notes           => <<"  NOTES");
1030         Takes a metarecord ID or a metarecord object and returns true
1031         if the metarecord already has an mvr associated with it.
1032         NOTES
1033
1034 sub biblio_mrid_check_mvr {
1035         my( $self, $client, $mrid ) = @_;
1036         my $mr; 
1037
1038         my $evt;
1039         if(ref($mrid)) { $mr = $mrid; } 
1040         else { ($mr, $evt) = _grab_metarecord($mrid); }
1041         return $evt if $evt;
1042
1043         warn "Checking mvr for mr " . $mr->id . "\n";
1044
1045         return _mr_to_mvr($mr) if $mr->mods();
1046         return undef;
1047 }
1048
1049 sub _grab_metarecord {
1050         my $mrid = shift;
1051         #my $e = OpenILS::Utils::Editor->new;
1052         my $e = new_editor();
1053         my $mr = $e->retrieve_metabib_metarecord($mrid) or return ( undef, $e->event );
1054         return ($mr);
1055 }
1056
1057
1058 __PACKAGE__->register_method(
1059         method  => "biblio_mrid_make_modsbatch",
1060         api_name        => "open-ils.search.biblio.metarecord.mods_slim.create",
1061         notes           => <<"  NOTES");
1062         Takes either a metarecord ID or a metarecord object.
1063         Forces the creations of an mvr for the given metarecord.
1064         The created mvr is returned.
1065         NOTES
1066
1067 sub biblio_mrid_make_modsbatch {
1068         my( $self, $client, $mrid ) = @_;
1069
1070         #my $e = OpenILS::Utils::Editor->new;
1071         my $e = new_editor();
1072
1073         my $mr;
1074         if( ref($mrid) ) {
1075                 $mr = $mrid;
1076                 $mrid = $mr->id;
1077         } else {
1078                 $mr = $e->retrieve_metabib_metarecord($mrid) 
1079                         or return $e->event;
1080         }
1081
1082         my $masterid = $mr->master_record;
1083         $logger->info("creating new mods batch for metarecord=$mrid, master record=$masterid");
1084
1085         my $ids = $U->storagereq(
1086                 'open-ils.storage.ordered.metabib.metarecord.records.staff.atomic', $mrid);
1087         return undef unless @$ids;
1088
1089         my $master = $e->retrieve_biblio_record_entry($masterid)
1090                 or return $e->event;
1091
1092         # start the mods batch
1093         my $u = OpenILS::Utils::ModsParser->new();
1094         $u->start_mods_batch( $master->marc );
1095
1096         # grab all of the sub-records and shove them into the batch
1097         my @ids = grep { $_ ne $masterid } @$ids;
1098         #my $subrecs = (@ids) ? $e->batch_retrieve_biblio_record_entry(\@ids) : [];
1099
1100         my $subrecs = [];
1101         if(@$ids) {
1102                 for my $i (@$ids) {
1103                         my $r = $e->retrieve_biblio_record_entry($i);
1104                         push( @$subrecs, $r ) if $r;
1105                 }
1106         }
1107
1108         for(@$subrecs) {
1109                 $logger->debug("adding record ".$_->id." to mods batch for metarecord=$mrid");
1110                 $u->push_mods_batch( $_->marc ) if $_->marc;
1111         }
1112
1113
1114         # finish up and send to the client
1115         my $mods = $u->finish_mods_batch();
1116         $mods->doc_id($mrid);
1117         $client->respond_complete($mods);
1118
1119
1120         # now update the mods string in the db
1121         my $string = OpenSRF::Utils::JSON->perl2JSON($mods->decast);
1122         $mr->mods($string);
1123
1124         #$e = OpenILS::Utils::Editor->new(xact => 1);
1125         $e = new_editor(xact => 1);
1126         $e->update_metabib_metarecord($mr) 
1127                 or $logger->error("Error setting mods text on metarecord $mrid : " . Dumper($e->event));
1128         $e->finish;
1129
1130         return undef;
1131 }
1132
1133
1134
1135
1136 # converts a mr id into a list of record ids
1137
1138 __PACKAGE__->register_method(
1139         method  => "biblio_mrid_to_record_ids",
1140         api_name        => "open-ils.search.biblio.metarecord_to_records",
1141 );
1142
1143 __PACKAGE__->register_method(
1144         method  => "biblio_mrid_to_record_ids",
1145         api_name        => "open-ils.search.biblio.metarecord_to_records.staff",
1146 );
1147
1148 sub biblio_mrid_to_record_ids {
1149         my( $self, $client, $mrid, $args ) = @_;
1150
1151         my $format      = $$args{format};
1152         my $org         = $$args{org};
1153         my $depth       = $$args{depth};
1154
1155         my $method = "open-ils.storage.ordered.metabib.metarecord.records.atomic";
1156         $method =~ s/atomic/staff\.atomic/o if $self->api_name =~ /staff/o; 
1157         my $recs = $U->storagereq($method, $mrid, $format, $org, $depth);
1158
1159         return { count => scalar(@$recs), ids => $recs };
1160 }
1161
1162
1163 __PACKAGE__->register_method(
1164         method  => "biblio_record_to_marc_html",
1165         api_name        => "open-ils.search.biblio.record.html" );
1166
1167 my $parser              = XML::LibXML->new();
1168 my $xslt                        = XML::LibXSLT->new();
1169 my $marc_sheet;
1170
1171 my $settings_client = OpenSRF::Utils::SettingsClient->new();
1172 sub biblio_record_to_marc_html {
1173         my( $self, $client, $recordid ) = @_;
1174
1175         if( !$marc_sheet ) {
1176                 my $dir = $settings_client->config_value( "dirs", "xsl" );
1177                 my $xsl = $settings_client->config_value(
1178                         "apps", "open-ils.search", "app_settings", "marc_html_xsl" );
1179
1180                 $xsl = $parser->parse_file("$dir/$xsl");
1181                 $marc_sheet = $xslt->parse_stylesheet( $xsl );
1182         }
1183
1184
1185         my $record = $apputils->simple_scalar_request(
1186                 "open-ils.cstore", 
1187                 "open-ils.cstore.direct.biblio.record_entry.retrieve",
1188                 $recordid );
1189
1190         my $xmldoc = $parser->parse_string($record->marc);
1191         my $html = $marc_sheet->transform($xmldoc);
1192         $html = $html->toString();
1193         return $html;
1194
1195 }
1196
1197
1198 =head duplicate
1199 __PACKAGE__->register_method(
1200         method  => "retrieve_all_copy_locations",
1201         api_name        => "open-ils.search.config.copy_location.retrieve.all" );
1202
1203 my $shelving_locations;
1204 sub retrieve_all_copy_locations {
1205         my( $self, $client ) = @_;
1206         if(!$shelving_locations) {
1207                 $shelving_locations = $apputils->simple_scalar_request(
1208                         "open-ils.cstore", 
1209                         "open-ils.cstore.direct.asset.copy_location.search.atomic",
1210                         { id => { "!=" => undef } }
1211                 );
1212         }
1213         return $shelving_locations;
1214 }
1215 =cut
1216
1217
1218
1219 __PACKAGE__->register_method(
1220         method  => "retrieve_all_copy_statuses",
1221         api_name        => "open-ils.search.config.copy_status.retrieve.all" );
1222
1223 my $copy_statuses;
1224 sub retrieve_all_copy_statuses {
1225         my( $self, $client ) = @_;
1226         return $copy_statuses if $copy_statuses;
1227         return $copy_statuses = 
1228                 new_editor()->retrieve_all_config_copy_status();
1229 }
1230
1231
1232 __PACKAGE__->register_method(
1233         method  => "copy_counts_per_org",
1234         api_name        => "open-ils.search.biblio.copy_counts.retrieve");
1235
1236 __PACKAGE__->register_method(
1237         method  => "copy_counts_per_org",
1238         api_name        => "open-ils.search.biblio.copy_counts.retrieve.staff");
1239
1240 sub copy_counts_per_org {
1241         my( $self, $client, $record_id ) = @_;
1242
1243         warn "Retreiveing copy copy counts for record $record_id and method " . $self->api_name . "\n";
1244
1245         my $method = "open-ils.storage.biblio.record_entry.global_copy_count.atomic";
1246         if($self->api_name =~ /staff/) { $method =~ s/atomic/staff\.atomic/; }
1247
1248         my $counts = $apputils->simple_scalar_request(
1249                 "open-ils.storage", $method, $record_id );
1250
1251         $counts = [ sort {$a->[0] <=> $b->[0]} @$counts ];
1252         return $counts;
1253 }
1254
1255
1256 __PACKAGE__->register_method(
1257         method          => "copy_count_summary",
1258         api_name        => "open-ils.search.biblio.copy_counts.summary.retrieve",
1259         notes           => <<"  NOTES");
1260         returns an array of these:
1261                 [ org_id, callnumber_label, <status1_count>, <status2_cout>,...]
1262                 where statusx is a copy status name.  the statuses are sorted
1263                 by id.
1264         NOTES
1265
1266 sub copy_count_summary {
1267         my( $self, $client, $rid, $org, $depth ) = @_;
1268         $org ||= 1;
1269         $depth ||= 0;
1270     my $data = $U->storagereq(
1271                 'open-ils.storage.biblio.record_entry.status_copy_count.atomic', $rid, $org, $depth );
1272
1273     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1274 }
1275
1276
1277
1278 =head
1279 __PACKAGE__->register_method(
1280         method          => "multiclass_search",
1281         api_name        => "open-ils.search.biblio.multiclass",
1282         notes           => <<"  NOTES");
1283                 Performs a multiclass search
1284                 PARAMS( searchBlob, org_unit, format, limit ) 
1285                 where searchBlob is defined like this:
1286                         { 
1287                                 "title" : { "term" : "water" }, 
1288                                 "author" : { "term" : "smith" }, 
1289                                 ... 
1290                         }
1291         NOTES
1292
1293 __PACKAGE__->register_method(
1294         method          => "multiclass_search",
1295         api_name        => "open-ils.search.biblio.multiclass.staff",
1296         notes           => "see open-ils.search.biblio.multiclass" );
1297
1298 sub multiclass_search {
1299         my( $self, $client, $searchBlob, $orgid, $format, $limit ) = @_;
1300
1301         $logger->debug("Performing multiclass search with org => $orgid, " .
1302                 "format => $format, limit => $limit, and search blob " . Dumper($searchBlob));
1303
1304         my $meth = 'open-ils.storage.metabib.post_filter.multiclass.search_fts.metarecord.atomic';
1305         if($self->api_name =~ /staff/) { $meth =~ s/metarecord\.atomic/metarecord.staff.atomic/; }
1306
1307
1308         my $records = $apputils->simplereq(
1309                 'open-ils.storage', $meth, 
1310                  org_unit => $orgid, searches => $searchBlob, format => $format, limit => $limit );
1311
1312         my $count = 0;
1313         my $recs = [];
1314
1315         if( ref($records) and $records->[0] and 
1316                 defined($records->[0]->[3])) { $count = $records->[0]->[3];}
1317
1318         for my $r (@$records) { push( @$recs, $r ) if ($r and $r->[0]); }
1319
1320         # records has the form: [ mrid, rank, singleRecord / 0, hitCount ];
1321         return { ids => $recs, count => $count };
1322 }
1323 =cut
1324
1325
1326 =head comment-1
1327 __PACKAGE__->register_method(
1328         method          => "multiclass_search",
1329         api_name                => "open-ils.search.biblio.multiclass",
1330         signature       => q/
1331                 Performs a multiclass search
1332                 @param args A names hash of arguments:
1333                         org_unit : The org to focus the search on
1334                         depth           : The search depth
1335                         format  : Item format
1336                         limit           : Return limit
1337                         offset  : Search offset
1338                         searches : A named hash of searches which has the following format:
1339                                 { 
1340                                         "title" : { "term" : "water" }, 
1341                                         "author" : { "term" : "smith" }, 
1342                                         ... 
1343                                 }
1344                 @return { ids : <array of ids>, count : hitcount }
1345         /
1346 );
1347
1348 __PACKAGE__->register_method(
1349         method          => "multiclass_search",
1350         api_name                => "open-ils.search.biblio.multiclass.staff",
1351         notes           => q/@see open-ils.search.biblio.multiclass/ );
1352
1353 sub multiclass_search {
1354         my( $self, $client, $args ) = @_;
1355
1356         $logger->debug("Performing multiclass search with args:\n" . Dumper($args));
1357         my $meth = 'open-ils.storage.metabib.post_filter.multiclass.search_fts.metarecord.atomic';
1358         if($self->api_name =~ /staff/) { $meth =~ s/metarecord\.atomic/metarecord.staff.atomic/; }
1359
1360         my $records = $apputils->simplereq( 'open-ils.storage', $meth, %$args );
1361
1362         my $count = 0;
1363         my $recs = [];
1364
1365         if( ref($records) and $records->[0] and 
1366                 defined($records->[0]->[3])) { $count = $records->[0]->[3];}
1367
1368         for my $r (@$records) { push( @$recs, $r ) if ($r and $r->[0]); }
1369
1370         return { ids => $recs, count => $count };
1371 }
1372
1373 =cut
1374
1375
1376
1377 __PACKAGE__->register_method(
1378         method          => "marc_search",
1379         api_name        => "open-ils.search.biblio.marc.staff");
1380
1381 __PACKAGE__->register_method(
1382         method          => "marc_search",
1383         api_name        => "open-ils.search.biblio.marc",
1384         notes           => <<"  NOTES");
1385                 Example:
1386                 open-ils.storage.biblio.full_rec.multi_search.atomic 
1387                 { "searches": [{"term":"harry","restrict": [{"tag":245,"subfield":"a"}]}], "org_unit": 1,
1388         "limit":5,"sort":"author","item_type":"g"}
1389         NOTES
1390
1391 sub marc_search {
1392         my( $self, $conn, $args, $limit, $offset ) = @_;
1393
1394         my $method = 'open-ils.storage.biblio.full_rec.multi_search';
1395         $method .= ".staff" if $self->api_name =~ /staff/;
1396         $method .= ".atomic";
1397
1398         $limit ||= 10;
1399         $offset ||= 0;
1400
1401         my @search;
1402         push( @search, ($_ => $$args{$_}) ) for (sort keys %$args);
1403         my $ckey = $pfx . md5_hex($method . OpenSRF::Utils::JSON->perl2JSON(\@search));
1404
1405         my $recs = search_cache($ckey, $offset, $limit);
1406
1407         if(!$recs) {
1408                 $recs = $U->storagereq($method, %$args) || [];
1409                 if( $recs ) {
1410                         put_cache($ckey, scalar(@$recs), $recs);
1411                         $recs = [ @$recs[$offset..($offset + ($limit - 1))] ];
1412                 } else {
1413                         $recs = [];
1414                 }
1415         }
1416
1417         my $count = 0;
1418         $count = $recs->[0]->[2] if $recs->[0] and $recs->[0]->[2];
1419         my @recs = map { $_->[0] } @$recs;
1420
1421         return { ids => \@recs, count => $count };
1422 }
1423
1424
1425 __PACKAGE__->register_method(
1426         method  => "biblio_search_isbn",
1427         api_name        => "open-ils.search.biblio.isbn",
1428 );
1429
1430 sub biblio_search_isbn { 
1431         my( $self, $client, $isbn ) = @_;
1432         $logger->debug("Searching ISBN $isbn");
1433         my $e = new_editor();
1434         my $recs = $U->storagereq(
1435                 'open-ils.storage.id_list.biblio.record_entry.search.isbn.atomic', $isbn );
1436         return { ids => $recs, count => scalar(@$recs) };
1437 }
1438
1439
1440 __PACKAGE__->register_method(
1441         method  => "biblio_search_issn",
1442         api_name        => "open-ils.search.biblio.issn",
1443 );
1444
1445 sub biblio_search_issn { 
1446         my( $self, $client, $issn ) = @_;
1447         $logger->debug("Searching ISSN $issn");
1448         my $e = new_editor();
1449         my $recs = $U->storagereq(
1450                 'open-ils.storage.id_list.biblio.record_entry.search.issn.atomic', $issn );
1451         return { ids => $recs, count => scalar(@$recs) };
1452 }
1453
1454
1455
1456
1457 __PACKAGE__->register_method(
1458         method  => "fetch_mods_by_copy",
1459         api_name        => "open-ils.search.biblio.mods_from_copy",
1460 );
1461
1462 sub fetch_mods_by_copy {
1463         my( $self, $client, $copyid ) = @_;
1464         my ($record, $evt) = $apputils->fetch_record_by_copy( $copyid );
1465         return $evt if $evt;
1466         return OpenILS::Event->new('ITEM_NOT_CATALOGED') unless $record->marc;
1467         return $apputils->record_to_mvr($record);
1468 }
1469
1470
1471
1472 # -------------------------------------------------------------------------------------
1473
1474 __PACKAGE__->register_method(
1475         method  => "cn_browse",
1476         api_name        => "open-ils.search.callnumber.browse.target",
1477         notes           => "Starts a callnumber browse"
1478         );
1479
1480 __PACKAGE__->register_method(
1481         method  => "cn_browse",
1482         api_name        => "open-ils.search.callnumber.browse.page_up",
1483         notes           => "Returns the previous page of callnumbers", 
1484         );
1485
1486 __PACKAGE__->register_method(
1487         method  => "cn_browse",
1488         api_name        => "open-ils.search.callnumber.browse.page_down",
1489         notes           => "Returns the next page of callnumbers", 
1490         );
1491
1492
1493 # RETURNS array of arrays like so: label, owning_lib, record, id
1494 sub cn_browse {
1495         my( $self, $client, @params ) = @_;
1496         my $method;
1497
1498         $method = 'open-ils.storage.asset.call_number.browse.target.atomic' 
1499                 if( $self->api_name =~ /target/ );
1500         $method = 'open-ils.storage.asset.call_number.browse.page_up.atomic'
1501                 if( $self->api_name =~ /page_up/ );
1502         $method = 'open-ils.storage.asset.call_number.browse.page_down.atomic'
1503                 if( $self->api_name =~ /page_down/ );
1504
1505         return $apputils->simplereq( 'open-ils.storage', $method, @params );
1506 }
1507 # -------------------------------------------------------------------------------------
1508
1509 __PACKAGE__->register_method(
1510         method => "fetch_cn",
1511     authoritative => 1,
1512         api_name => "open-ils.search.callnumber.retrieve",
1513         notes           => "retrieves a callnumber based on ID",
1514         );
1515
1516 sub fetch_cn {
1517         my( $self, $client, $id ) = @_;
1518         my( $cn, $evt ) = $apputils->fetch_callnumber( $id );
1519         return $evt if $evt;
1520         return $cn;
1521 }
1522
1523 __PACKAGE__->register_method (
1524         method          => "fetch_copy_by_cn",
1525         api_name                => 'open-ils.search.copies_by_call_number.retrieve',
1526         signature       => q/
1527                 Returns an array of copy id's by callnumber id
1528                 @param cnid The callnumber id
1529                 @return An array of copy ids
1530         /
1531 );
1532
1533 sub fetch_copy_by_cn {
1534         my( $self, $conn, $cnid ) = @_;
1535         return $U->cstorereq(
1536                 'open-ils.cstore.direct.asset.copy.id_list.atomic', 
1537                 { call_number => $cnid, deleted => 'f' } );
1538 }
1539
1540 __PACKAGE__->register_method (
1541         method          => 'fetch_cn_by_info',
1542         api_name                => 'open-ils.search.call_number.retrieve_by_info',
1543         signature       => q/
1544                 @param label The callnumber label
1545                 @param record The record the cn is attached to
1546                 @param org The owning library of the cn
1547                 @return The callnumber object
1548         /
1549 );
1550
1551
1552 sub fetch_cn_by_info {
1553         my( $self, $conn, $label, $record, $org ) = @_;
1554         return $U->cstorereq(
1555                 'open-ils.cstore.direct.asset.call_number.search',
1556                 { label => $label, record => $record, owning_lib => $org, deleted => 'f' });
1557 }
1558
1559
1560                 
1561
1562
1563 __PACKAGE__->register_method (
1564         method => 'bib_extras',
1565         api_name => 'open-ils.search.biblio.lit_form_map.retrieve.all');
1566 __PACKAGE__->register_method (
1567         method => 'bib_extras',
1568         api_name => 'open-ils.search.biblio.item_form_map.retrieve.all');
1569 __PACKAGE__->register_method (
1570         method => 'bib_extras',
1571         api_name => 'open-ils.search.biblio.item_type_map.retrieve.all');
1572 __PACKAGE__->register_method (
1573         method => 'bib_extras',
1574         api_name => 'open-ils.search.biblio.bib_level_map.retrieve.all');
1575 __PACKAGE__->register_method (
1576         method => 'bib_extras',
1577         api_name => 'open-ils.search.biblio.audience_map.retrieve.all');
1578
1579 sub bib_extras {
1580         my $self = shift;
1581
1582         my $e = new_editor();
1583
1584         return $e->retrieve_all_config_lit_form_map()
1585                 if( $self->api_name =~ /lit_form/ );
1586
1587         return $e->retrieve_all_config_item_form_map()
1588                 if( $self->api_name =~ /item_form_map/ );
1589
1590         return $e->retrieve_all_config_item_type_map()
1591                 if( $self->api_name =~ /item_type_map/ );
1592
1593         return $e->retrieve_all_config_bib_level_map()
1594                 if( $self->api_name =~ /bib_level_map/ );
1595
1596         return $e->retrieve_all_config_audience_map()
1597                 if( $self->api_name =~ /audience_map/ );
1598
1599         return [];
1600 }
1601
1602
1603
1604 __PACKAGE__->register_method(
1605         method  => 'fetch_slim_record',
1606         api_name        => 'open-ils.search.biblio.record_entry.slim.retrieve',
1607         signature=> q/
1608                 Returns a biblio.record_entry without the attached marcxml
1609         /
1610 );
1611
1612 sub fetch_slim_record {
1613         my( $self, $conn, $ids ) = @_;
1614
1615         #my $editor = OpenILS::Utils::Editor->new;
1616         my $editor = new_editor();
1617         my @res;
1618         for( @$ids ) {
1619                 return $editor->event unless
1620                         my $r = $editor->retrieve_biblio_record_entry($_);
1621                 $r->clear_marc;
1622                 push(@res, $r);
1623         }
1624         return \@res;
1625 }
1626
1627
1628
1629 __PACKAGE__->register_method(
1630         method => 'rec_to_mr_rec_descriptors',
1631         api_name        => 'open-ils.search.metabib.record_to_descriptors',
1632         signature       => q/
1633                 specialized method...
1634                 Given a biblio record id or a metarecord id, 
1635                 this returns a list of metabib.record_descriptor
1636                 objects that live within the same metarecord
1637                 @param args Object of args including:
1638         /
1639 );
1640
1641 sub rec_to_mr_rec_descriptors {
1642         my( $self, $conn, $args ) = @_;
1643
1644         my $rec = $$args{record};
1645         my $mrec        = $$args{metarecord};
1646         my $item_forms = $$args{item_forms};
1647         my $item_types  = $$args{item_types};
1648         my $item_lang   = $$args{item_lang};
1649
1650         my $e = new_editor();
1651         my $recs;
1652
1653         if( !$mrec ) {
1654                 my $map = $e->search_metabib_metarecord_source_map({source => $rec});
1655                 return $e->event unless @$map;
1656                 $mrec = $$map[0]->metarecord;
1657         }
1658
1659         $recs = $e->search_metabib_metarecord_source_map({metarecord => $mrec});
1660         return $e->event unless @$recs;
1661
1662         my @recs = map { $_->source } @$recs;
1663         my $search = { record => \@recs };
1664         $search->{item_form} = $item_forms if $item_forms and @$item_forms;
1665         $search->{item_type} = $item_types if $item_types and @$item_types;
1666         $search->{item_lang} = $item_lang if $item_lang;
1667
1668         my $desc = $e->search_metabib_record_descriptor($search);
1669
1670         return { metarecord => $mrec, descriptors => $desc };
1671 }
1672
1673
1674
1675
1676 __PACKAGE__->register_method(
1677         method => 'copies_created_on',  
1678 );
1679
1680
1681 sub copies_created_on {
1682         my( $self, $conn, $auth, $org, $date ) = @_;
1683         my $e = new_editor(authtoken=>$auth);
1684         return $e->event unless $e->checkauth;
1685 }
1686
1687
1688 __PACKAGE__->register_method(
1689         method => 'fetch_age_protect',
1690         api_name => 'open-ils.search.copy.age_protect.retrieve.all',
1691 );
1692
1693 sub fetch_age_protect {
1694         return new_editor()->retrieve_all_config_rule_age_hold_protect();
1695 }
1696
1697
1698 __PACKAGE__->register_method(
1699         method => 'copies_by_cn_label',
1700         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label',
1701 );
1702
1703 __PACKAGE__->register_method(
1704         method => 'copies_by_cn_label',
1705         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label.staff',
1706 );
1707
1708 sub copies_by_cn_label {
1709         my( $self, $conn, $record, $label, $circ_lib ) = @_;
1710         my $e = new_editor();
1711         my $cns = $e->search_asset_call_number({record => $record, label => $label, deleted => 'f'}, {idlist=>1});
1712         return [] unless @$cns;
1713
1714         # show all non-deleted copies in the staff client ...
1715         if ($self->api_name =~ /staff$/o) {
1716                 return $e->search_asset_copy({call_number => $cns, circ_lib => $circ_lib, deleted => 'f'}, {idlist=>1});
1717         }
1718
1719         # ... otherwise, grab the copies ...
1720         my $copies = $e->search_asset_copy(
1721                 [ {call_number => $cns, circ_lib => $circ_lib, deleted => 'f', opac_visible => 't'},
1722                   {flesh => 1, flesh_fields => { acp => [ qw/location status/] } }
1723                 ]
1724         );
1725
1726         # ... and test for location and status visibility
1727         return [ map { ($U->is_true($_->location->opac_visible) && $U->is_true($_->status->opac_visible)) ? ($_->id) : () } @$copies ];
1728 }
1729
1730
1731
1732 1;
1733
1734