]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Biblio.pm
add copy location display based on switch
[working/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/^\s+|\s+$//og;
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     $arghash->{preferred_language} = $U->get_org_locale($arghash->{org_unit})
542         unless $arghash->{preferred_language};
543
544         $method = $self->method_lookup($method);
545     my ($data) = $method->run($arghash, $docache);
546
547     $arghash->{limit} = $ol if $ol;
548     $data->{compiled_search} = $arghash;
549     $data->{query} = $orig_query;
550
551     $logger->info("compiled search is " . OpenSRF::Utils::JSON->perl2JSON($arghash));
552
553     return $data;
554 }
555
556 __PACKAGE__->register_method(
557         method          => 'cat_search_z_style_wrapper',
558         api_name        => 'open-ils.search.biblio.zstyle',
559         stream          => 1,
560         signature       => q/@see open-ils.search.biblio.multiclass/);
561
562 sub cat_search_z_style_wrapper {
563         my $self = shift;
564         my $client = shift;
565         my $authtoken = shift;
566         my $args = shift;
567
568         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
569
570         my $ou = $cstore->request(
571                 'open-ils.cstore.direct.actor.org_unit.search',
572                 { parent_ou => undef }
573         )->gather(1);
574
575         my $result = { service => 'native-evergreen-catalog', records => [] };
576         my $searchhash = { limit => $$args{limit}, offset => $$args{offset}, org_unit => $ou->id };
577
578         $$searchhash{searches}{title}{term} = $$args{search}{title} if $$args{search}{title};
579         $$searchhash{searches}{author}{term} = $$args{search}{author} if $$args{search}{author};
580         $$searchhash{searches}{subject}{term} = $$args{search}{subject} if $$args{search}{subject};
581         $$searchhash{searches}{keyword}{term} = $$args{search}{keyword} if $$args{search}{keyword};
582
583         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{tcn} if $$args{search}{tcn};
584         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{isbn} if $$args{search}{isbn};
585         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{issn} if $$args{search}{issn};
586         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{publisher} if $$args{search}{publisher};
587         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{pubdate} if $$args{search}{pubdate};
588         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{item_type} if $$args{search}{item_type};
589
590         my $list = the_quest_for_knowledge( $self, $client, $searchhash );
591
592         if ($list->{count} > 0) {
593                 $result->{count} = $list->{count};
594
595                 my $records = $cstore->request(
596                         'open-ils.cstore.direct.biblio.record_entry.search.atomic',
597                         { id => [ map { ( $_->[0] ) } @{$list->{ids}} ] }
598                 )->gather(1);
599
600                 for my $rec ( @$records ) {
601                         
602                         my $u = OpenILS::Utils::ModsParser->new();
603                         $u->start_mods_batch( $rec->marc );
604                         my $mods = $u->finish_mods_batch();
605
606                         push @{ $result->{records} }, { mvr => $mods, marcxml => $rec->marc, bibid => $rec->id };
607
608                 }
609
610         }
611
612     $cstore->disconnect();
613         return $result;
614 }
615
616 # ----------------------------------------------------------------------------
617 # These are the main OPAC search methods
618 # ----------------------------------------------------------------------------
619
620 __PACKAGE__->register_method(
621         method          => 'the_quest_for_knowledge',
622         api_name                => 'open-ils.search.biblio.multiclass',
623         signature       => q/
624                 Performs a multi class bilbli or metabib search
625                 @param searchhash A search object layed out like so:
626                         searches : { "$class" : "$value", ...}
627                         org_unit : The org id to focus the search at
628                         depth           : The org depth
629                         limit           : The search limit
630                         offset  : The search offset
631                         format  : The MARC format
632                         sort            : What field to sort the results on [ author | title | pubdate ]
633                         sort_dir        : What direction do we sort? [ asc | desc ]
634                 @return An object of the form 
635                         { "count" : $count, "ids" : [ [ $id, $relevancy, $total ], ...] }
636         /
637 );
638
639 __PACKAGE__->register_method(
640         method          => 'the_quest_for_knowledge',
641         api_name                => 'open-ils.search.biblio.multiclass.staff',
642         signature       => q/@see open-ils.search.biblio.multiclass/);
643 __PACKAGE__->register_method(
644         method          => 'the_quest_for_knowledge',
645         api_name                => 'open-ils.search.metabib.multiclass',
646         signature       => q/@see open-ils.search.biblio.multiclass/);
647 __PACKAGE__->register_method(
648         method          => 'the_quest_for_knowledge',
649         api_name                => 'open-ils.search.metabib.multiclass.staff',
650         signature       => q/@see open-ils.search.biblio.multiclass/);
651
652 sub the_quest_for_knowledge {
653         my( $self, $conn, $searchhash, $docache ) = @_;
654
655         return { count => 0 } unless $searchhash and
656                 ref $searchhash->{searches} eq 'HASH';
657
658         my $method = 'open-ils.storage.biblio.multiclass.search_fts';
659         my $ismeta = 0;
660         my @recs;
661
662         if($self->api_name =~ /metabib/) {
663                 $ismeta = 1;
664                 $method =~ s/biblio/metabib/o;
665         }
666
667
668         my $offset      = $searchhash->{offset} || 0;
669         my $limit       = $searchhash->{limit} || 10;
670         my $end         = $offset + $limit - 1;
671
672         # do some simple sanity checking
673         if(!$searchhash->{searches} or
674                 ( !grep { /^(?:title|author|subject|series|keyword)/ } keys %{$searchhash->{searches}} ) ) {
675                 return { count => 0 };
676         }
677
678
679         my $maxlimit = 5000;
680         $searchhash->{offset}   = 0;
681         $searchhash->{limit}            = $maxlimit;
682
683         return { count => 0 } if $offset > $maxlimit;
684
685         my @search;
686         push( @search, ($_ => $$searchhash{$_})) for (sort keys %$searchhash);
687         my $s = OpenSRF::Utils::JSON->perl2JSON(\@search);
688         my $ckey = $pfx . md5_hex($method . $s);
689
690         $logger->info("bib search for: $s");
691
692         $searchhash->{limit} -= $offset;
693
694
695     my $trim = 0;
696         my $result = ($docache) ? search_cache($ckey, $offset, $limit) : undef;
697
698         if(!$result) {
699
700                 $method .= ".staff" if($self->api_name =~ /staff/);
701                 $method .= ".atomic";
702         
703                 for (keys %$searchhash) { 
704                         delete $$searchhash{$_} 
705                                 unless defined $$searchhash{$_}; 
706                 }
707         
708                 $result = $U->storagereq( $method, %$searchhash );
709         $trim = 1;
710
711         } else { 
712                 $docache = 0; 
713         }
714
715         return {count => 0} unless ($result && $$result[0]);
716
717         @recs = @$result;
718
719         my $count = ($ismeta) ? $result->[0]->[3] : $result->[0]->[2];
720
721         if($docache) {
722                 # If we didn't get this data from the cache, put it into the cache
723                 # then return the correct offset of records
724                 $logger->debug("putting search cache $ckey\n");
725                 put_cache($ckey, $count, \@recs);
726         }
727
728     if($trim) {
729         # if we have the full set of data, trim out 
730         # the requested chunk based on limit and offset
731         my @t;
732         for ($offset..$end) {
733             last unless $recs[$_];
734             push(@t, $recs[$_]);
735         }
736         @recs = @t;
737     }
738
739         return { ids => \@recs, count => $count };
740 }
741
742
743 __PACKAGE__->register_method(
744         method          => 'staged_search',
745         api_name        => 'open-ils.search.biblio.multiclass.staged');
746 __PACKAGE__->register_method(
747         method          => 'staged_search',
748         api_name        => 'open-ils.search.biblio.multiclass.staged.staff',
749         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
750 __PACKAGE__->register_method(
751         method          => 'staged_search',
752         api_name        => 'open-ils.search.metabib.multiclass.staged',
753         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
754 __PACKAGE__->register_method(
755         method          => 'staged_search',
756         api_name        => 'open-ils.search.metabib.multiclass.staged.staff',
757         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
758
759 sub staged_search {
760         my($self, $conn, $search_hash, $docache) = @_;
761
762     my $method = ($self->api_name =~ /metabib/) ?
763         'open-ils.storage.metabib.multiclass.staged.search_fts':
764         'open-ils.storage.biblio.multiclass.staged.search_fts';
765
766     $method .= '.staff' if $self->api_name =~ /staff$/;
767     $method .= '.atomic';
768
769     my $search_duration;
770     my $user_offset = $search_hash->{offset} || 0; # user-specified offset
771     my $user_limit = $search_hash->{limit} || 10;
772     $user_offset = ($user_offset >= 0) ? $user_offset : 0;
773     $user_limit = ($user_limit >= 0) ? $user_limit : 10;
774
775
776     # we're grabbing results on a per-superpage basis, which means the 
777     # limit and offset should coincide with superpage boundaries
778     $search_hash->{offset} = 0;
779     $search_hash->{limit} = $superpage_size;
780
781     # force a well-known check_limit
782     $search_hash->{check_limit} = $superpage_size; 
783     # restrict total tested to superpage size * number of superpages
784     $search_hash->{core_limit} = $superpage_size * $max_superpages;
785
786     # Set the configured estimation strategy, defaults to 'inclusion'.
787         my $estimation_strategy = OpenSRF::Utils::SettingsClient
788         ->new
789         ->config_value(
790             apps => 'open-ils.search', app_settings => 'estimation_strategy'
791         ) || 'inclusion';
792         $search_hash->{estimation_strategy} = $estimation_strategy;
793
794     # pull any existing results from the cache
795     my $key = search_cache_key($method, $search_hash);
796     my $cache_data = $cache->get_cache($key) || {};
797
798     # keep retrieving results until we find enough to 
799     # fulfill the user-specified limit and offset
800     my $all_results = [];
801     my $page; # current superpage
802     my $est_hit_count = 0;
803     my $current_page_summary = {};
804     my $global_summary = {checked => 0, visible => 0, excluded => 0, deleted => 0, total => 0};
805     my $is_real_hit_count = 0;
806
807     for($page = 0; $page < $max_superpages; $page++) {
808
809         my $data = $cache_data->{$page};
810         my $results;
811         my $summary;
812
813         $logger->debug("staged search: analyzing superpage $page");
814
815         if($data) {
816             # this window of results is already cached
817             $logger->debug("staged search: found cached results");
818             $summary = $data->{summary};
819             $results = $data->{results};
820
821         } else {
822             # retrieve the window of results from the database
823             $logger->debug("staged search: fetching results from the database");
824             $search_hash->{skip_check} = $page * $superpage_size;
825             my $start = time;
826             $results = $U->storagereq($method, %$search_hash);
827             $search_duration = time - $start;
828             $logger->info("staged search: DB call took $search_duration seconds");
829             $summary = shift(@$results);
830
831             unless($summary) {
832                 $logger->info("search timed out: duration=$search_duration: params=".
833                     OpenSRF::Utils::JSON->perl2JSON($search_hash));
834                 return {count => 0};
835             }
836
837             my $hc = $summary->{estimated_hit_count} || $summary->{visible};
838             if($hc == 0) {
839                 $logger->info("search returned 0 results: duration=$search_duration: params=".
840                     OpenSRF::Utils::JSON->perl2JSON($search_hash));
841             }
842
843             # Create backwards-compatible result structures
844             if($self->api_name =~ /biblio/) {
845                 $results = [map {[$_->{id}]} @$results];
846             } else {
847                 $results = [map {[$_->{id}, $_->{rel}, $_->{record}]} @$results];
848             }
849
850             $results = [grep {defined $_->[0]} @$results];
851             cache_staged_search_page($key, $page, $summary, $results) if $docache;
852         }
853
854         $current_page_summary = $summary;
855
856         # add the new set of results to the set under construction
857         push(@$all_results, @$results);
858
859         my $current_count = scalar(@$all_results);
860
861         $est_hit_count = $summary->{estimated_hit_count} || $summary->{visible}
862             if $page == 0;
863
864         $logger->debug("staged search: located $current_count, with estimated hits=".
865             $summary->{estimated_hit_count}." : visible=".$summary->{visible}.", checked=".$summary->{checked});
866
867                 if (defined($summary->{estimated_hit_count})) {
868                         $global_summary->{checked} += $summary->{checked};
869                         $global_summary->{visible} += $summary->{visible};
870                         $global_summary->{excluded} += $summary->{excluded};
871                         $global_summary->{deleted} += $summary->{deleted};
872                         $global_summary->{total} = $summary->{total};
873                 }
874
875         # we've found all the possible hits
876         last if $current_count == $summary->{visible}
877             and not defined $summary->{estimated_hit_count};
878
879         # we've found enough results to satisfy the requested limit/offset
880         last if $current_count >= ($user_limit + $user_offset);
881
882         # we've scanned all possible hits
883         if($summary->{checked} < $superpage_size) {
884             $est_hit_count = scalar(@$all_results);
885             # we have all possible results in hand, so we know the final hit count
886             $is_real_hit_count = 1;
887             last;
888         }
889     }
890
891     my @results = grep {defined $_} @$all_results[$user_offset..($user_offset + $user_limit - 1)];
892
893         # refine the estimate if we have more than one superpage
894         if ($page > 0 and not $is_real_hit_count) {
895                 if ($global_summary->{checked} >= $global_summary->{total}) {
896                         $est_hit_count = $global_summary->{visible};
897                 } else {
898                         my $updated_hit_count = $U->storagereq(
899                                 'open-ils.storage.fts_paging_estimate',
900                                 $global_summary->{checked},
901                                 $global_summary->{visible},
902                                 $global_summary->{excluded},
903                                 $global_summary->{deleted},
904                                 $global_summary->{total}
905                         );
906                         $est_hit_count = $updated_hit_count->{$estimation_strategy};
907                 }
908         }
909
910     return {
911         count => $est_hit_count,
912         core_limit => $search_hash->{core_limit},
913         superpage_size => $search_hash->{check_limit},
914         superpage_summary => $current_page_summary,
915         ids => \@results
916     };
917 }
918
919 # creates a unique token to represent the query in the cache
920 sub search_cache_key {
921     my $method = shift;
922     my $search_hash = shift;
923         my @sorted;
924     for my $key (sort keys %$search_hash) {
925             push(@sorted, ($key => $$search_hash{$key})) 
926             unless $key eq 'limit' or 
927                 $key eq 'offset' or 
928                 $key eq 'skip_check';
929     }
930         my $s = OpenSRF::Utils::JSON->perl2JSON(\@sorted);
931         return $pfx . md5_hex($method . $s);
932 }
933
934 sub cache_staged_search_page {
935     # puts this set of results into the cache
936     my($key, $page, $summary, $results) = @_;
937     my $data = $cache->get_cache($key);
938     $data ||= {};
939     $data->{$page} = {
940         summary => $summary,
941         results => $results
942     };
943
944     $logger->info("staged search: cached with key=$key, superpage=$page, estimated=".
945         $summary->{estimated_hit_count}.", visible=".$summary->{visible});
946
947     $cache->put_cache($key, $data, $cache_timeout);
948 }
949
950 sub search_cache {
951
952         my $key         = shift;
953         my $offset      = shift;
954         my $limit       = shift;
955         my $start       = $offset;
956         my $end         = $offset + $limit - 1;
957
958         $logger->debug("searching cache for $key : $start..$end\n");
959
960         return undef unless $cache;
961         my $data = $cache->get_cache($key);
962
963         return undef unless $data;
964
965         my $count = $data->[0];
966         $data = $data->[1];
967
968         return undef unless $offset < $count;
969
970         my @result;
971         for( my $i = $offset; $i <= $end; $i++ ) {
972                 last unless my $d = $$data[$i];
973                 push( @result, $d );
974         }
975
976         $logger->debug("search_cache found ".scalar(@result)." items for count=$count, start=$start, end=$end");
977
978         return \@result;
979 }
980
981
982 sub put_cache {
983         my( $key, $count, $data ) = @_;
984         return undef unless $cache;
985         $logger->debug("search_cache putting ".
986                 scalar(@$data)." items at key $key with timeout $cache_timeout");
987         $cache->put_cache($key, [ $count, $data ], $cache_timeout);
988 }
989
990
991
992
993
994
995 __PACKAGE__->register_method(
996         method  => "biblio_mrid_to_modsbatch_batch",
997         api_name        => "open-ils.search.biblio.metarecord.mods_slim.batch.retrieve");
998
999 sub biblio_mrid_to_modsbatch_batch {
1000         my( $self, $client, $mrids) = @_;
1001         warn "Performing mrid_to_modsbatch_batch...";
1002         my @mods;
1003         my $method = $self->method_lookup("open-ils.search.biblio.metarecord.mods_slim.retrieve");
1004         for my $id (@$mrids) {
1005                 next unless defined $id;
1006                 my ($m) = $method->run($id);
1007                 push @mods, $m;
1008         }
1009         return \@mods;
1010 }
1011
1012
1013 __PACKAGE__->register_method(
1014         method  => "biblio_mrid_to_modsbatch",
1015         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve",
1016         notes           => <<"  NOTES");
1017         Returns the mvr associated with a given metarecod. If none exists, 
1018         it is created.
1019         NOTES
1020
1021 __PACKAGE__->register_method(
1022         method  => "biblio_mrid_to_modsbatch",
1023         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve.staff",
1024         notes           => <<"  NOTES");
1025         Returns the mvr associated with a given metarecod. If none exists, 
1026         it is created.
1027         NOTES
1028
1029 sub biblio_mrid_to_modsbatch {
1030         my( $self, $client, $mrid, $args) = @_;
1031
1032         warn "Grabbing mvr for $mrid\n";
1033
1034         my ($mr, $evt) = _grab_metarecord($mrid);
1035         return $evt unless $mr;
1036
1037         my $mvr = biblio_mrid_check_mvr($self, $client, $mr);
1038         $mvr = biblio_mrid_make_modsbatch( $self, $client, $mr ) unless $mvr;
1039
1040         return $mvr unless ref($args);  
1041
1042         # Here we find the lead record appropriate for the given filters 
1043         # and use that for the title and author of the metarecord
1044         my $format      = $$args{format};
1045         my $org         = $$args{org};
1046         my $depth       = $$args{depth};
1047
1048         return $mvr unless $format or $org or $depth;
1049
1050         my $method = "open-ils.storage.ordered.metabib.metarecord.records";
1051         $method = "$method.staff" if $self->api_name =~ /staff/o; 
1052
1053         my $rec = $U->storagereq($method, $format, $org, $depth, 1);
1054
1055         if( my $mods = $U->record_to_mvr($rec) ) {
1056
1057                 $mvr->title($mods->title);
1058                 $mvr->title($mods->author);
1059                 $logger->debug("mods_slim updating title and ".
1060                         "author in mvr with ".$mods->title." : ".$mods->author);
1061         }
1062
1063         return $mvr;
1064 }
1065
1066 # converts a metarecord to an mvr
1067 sub _mr_to_mvr {
1068         my $mr = shift;
1069         my $perl = OpenSRF::Utils::JSON->JSON2perl($mr->mods());
1070         return Fieldmapper::metabib::virtual_record->new($perl);
1071 }
1072
1073 # checks to see if a metarecord has mods, if so returns true;
1074
1075 __PACKAGE__->register_method(
1076         method  => "biblio_mrid_check_mvr",
1077         api_name        => "open-ils.search.biblio.metarecord.mods_slim.check",
1078         notes           => <<"  NOTES");
1079         Takes a metarecord ID or a metarecord object and returns true
1080         if the metarecord already has an mvr associated with it.
1081         NOTES
1082
1083 sub biblio_mrid_check_mvr {
1084         my( $self, $client, $mrid ) = @_;
1085         my $mr; 
1086
1087         my $evt;
1088         if(ref($mrid)) { $mr = $mrid; } 
1089         else { ($mr, $evt) = _grab_metarecord($mrid); }
1090         return $evt if $evt;
1091
1092         warn "Checking mvr for mr " . $mr->id . "\n";
1093
1094         return _mr_to_mvr($mr) if $mr->mods();
1095         return undef;
1096 }
1097
1098 sub _grab_metarecord {
1099         my $mrid = shift;
1100         #my $e = OpenILS::Utils::Editor->new;
1101         my $e = new_editor();
1102         my $mr = $e->retrieve_metabib_metarecord($mrid) or return ( undef, $e->event );
1103         return ($mr);
1104 }
1105
1106
1107 __PACKAGE__->register_method(
1108         method  => "biblio_mrid_make_modsbatch",
1109         api_name        => "open-ils.search.biblio.metarecord.mods_slim.create",
1110         notes           => <<"  NOTES");
1111         Takes either a metarecord ID or a metarecord object.
1112         Forces the creations of an mvr for the given metarecord.
1113         The created mvr is returned.
1114         NOTES
1115
1116 sub biblio_mrid_make_modsbatch {
1117         my( $self, $client, $mrid ) = @_;
1118
1119         #my $e = OpenILS::Utils::Editor->new;
1120         my $e = new_editor();
1121
1122         my $mr;
1123         if( ref($mrid) ) {
1124                 $mr = $mrid;
1125                 $mrid = $mr->id;
1126         } else {
1127                 $mr = $e->retrieve_metabib_metarecord($mrid) 
1128                         or return $e->event;
1129         }
1130
1131         my $masterid = $mr->master_record;
1132         $logger->info("creating new mods batch for metarecord=$mrid, master record=$masterid");
1133
1134         my $ids = $U->storagereq(
1135                 'open-ils.storage.ordered.metabib.metarecord.records.staff.atomic', $mrid);
1136         return undef unless @$ids;
1137
1138         my $master = $e->retrieve_biblio_record_entry($masterid)
1139                 or return $e->event;
1140
1141         # start the mods batch
1142         my $u = OpenILS::Utils::ModsParser->new();
1143         $u->start_mods_batch( $master->marc );
1144
1145         # grab all of the sub-records and shove them into the batch
1146         my @ids = grep { $_ ne $masterid } @$ids;
1147         #my $subrecs = (@ids) ? $e->batch_retrieve_biblio_record_entry(\@ids) : [];
1148
1149         my $subrecs = [];
1150         if(@$ids) {
1151                 for my $i (@$ids) {
1152                         my $r = $e->retrieve_biblio_record_entry($i);
1153                         push( @$subrecs, $r ) if $r;
1154                 }
1155         }
1156
1157         for(@$subrecs) {
1158                 $logger->debug("adding record ".$_->id." to mods batch for metarecord=$mrid");
1159                 $u->push_mods_batch( $_->marc ) if $_->marc;
1160         }
1161
1162
1163         # finish up and send to the client
1164         my $mods = $u->finish_mods_batch();
1165         $mods->doc_id($mrid);
1166         $client->respond_complete($mods);
1167
1168
1169         # now update the mods string in the db
1170         my $string = OpenSRF::Utils::JSON->perl2JSON($mods->decast);
1171         $mr->mods($string);
1172
1173         #$e = OpenILS::Utils::Editor->new(xact => 1);
1174         $e = new_editor(xact => 1);
1175         $e->update_metabib_metarecord($mr) 
1176                 or $logger->error("Error setting mods text on metarecord $mrid : " . Dumper($e->event));
1177         $e->finish;
1178
1179         return undef;
1180 }
1181
1182
1183
1184
1185 # converts a mr id into a list of record ids
1186
1187 __PACKAGE__->register_method(
1188         method  => "biblio_mrid_to_record_ids",
1189         api_name        => "open-ils.search.biblio.metarecord_to_records",
1190 );
1191
1192 __PACKAGE__->register_method(
1193         method  => "biblio_mrid_to_record_ids",
1194         api_name        => "open-ils.search.biblio.metarecord_to_records.staff",
1195 );
1196
1197 sub biblio_mrid_to_record_ids {
1198         my( $self, $client, $mrid, $args ) = @_;
1199
1200         my $format      = $$args{format};
1201         my $org         = $$args{org};
1202         my $depth       = $$args{depth};
1203
1204         my $method = "open-ils.storage.ordered.metabib.metarecord.records.atomic";
1205         $method =~ s/atomic/staff\.atomic/o if $self->api_name =~ /staff/o; 
1206         my $recs = $U->storagereq($method, $mrid, $format, $org, $depth);
1207
1208         return { count => scalar(@$recs), ids => $recs };
1209 }
1210
1211
1212 __PACKAGE__->register_method(
1213         method  => "biblio_record_to_marc_html",
1214         api_name        => "open-ils.search.biblio.record.html" );
1215
1216 __PACKAGE__->register_method(
1217         method  => "biblio_record_to_marc_html",
1218         api_name        => "open-ils.search.authority.to_html" );
1219
1220 my $parser = XML::LibXML->new();
1221 my $xslt = XML::LibXSLT->new();
1222 my $marc_sheet;
1223 my $slim_marc_sheet;
1224 my $settings_client = OpenSRF::Utils::SettingsClient->new();
1225
1226 sub biblio_record_to_marc_html {
1227         my($self, $client, $recordid, $slim, $marcxml) = @_;
1228
1229     my $sheet;
1230         my $dir = $settings_client->config_value("dirs", "xsl");
1231
1232     if($slim) {
1233         unless($slim_marc_sheet) {
1234                     my $xsl = $settings_client->config_value(
1235                             "apps", "open-ils.search", "app_settings", 'marc_html_xsl_slim');
1236             if($xsl) {
1237                         $xsl = $parser->parse_file("$dir/$xsl");
1238                         $slim_marc_sheet = $xslt->parse_stylesheet($xsl);
1239             }
1240         }
1241         $sheet = $slim_marc_sheet;
1242     }
1243
1244     unless($sheet) {
1245         unless($marc_sheet) {
1246             my $xsl_key = ($slim) ? 'marc_html_xsl_slim' : 'marc_html_xsl';
1247                     my $xsl = $settings_client->config_value(
1248                             "apps", "open-ils.search", "app_settings", 'marc_html_xsl');
1249                     $xsl = $parser->parse_file("$dir/$xsl");
1250                     $marc_sheet = $xslt->parse_stylesheet($xsl);
1251         }
1252         $sheet = $marc_sheet;
1253     }
1254
1255     my $record;
1256     unless($marcxml) {
1257         my $e = new_editor();
1258         if($self->api_name =~ /authority/) {
1259             $record = $e->retrieve_authority_record_entry($recordid)
1260                 or return $e->event;
1261         } else {
1262             $record = $e->retrieve_biblio_record_entry($recordid)
1263                 or return $e->event;
1264         }
1265         $marcxml = $record->marc;
1266     }
1267
1268         my $xmldoc = $parser->parse_string($marcxml);
1269         my $html = $sheet->transform($xmldoc);
1270         return $html->documentElement->toString();
1271 }
1272
1273
1274
1275 __PACKAGE__->register_method(
1276         method  => "retrieve_all_copy_statuses",
1277         api_name        => "open-ils.search.config.copy_status.retrieve.all" );
1278
1279 my $copy_statuses;
1280 sub retrieve_all_copy_statuses {
1281         my( $self, $client ) = @_;
1282         return $copy_statuses if $copy_statuses;
1283         return $copy_statuses = 
1284                 new_editor()->retrieve_all_config_copy_status();
1285 }
1286
1287
1288 __PACKAGE__->register_method(
1289         method  => "copy_counts_per_org",
1290         api_name        => "open-ils.search.biblio.copy_counts.retrieve");
1291
1292 __PACKAGE__->register_method(
1293         method  => "copy_counts_per_org",
1294         api_name        => "open-ils.search.biblio.copy_counts.retrieve.staff");
1295
1296 sub copy_counts_per_org {
1297         my( $self, $client, $record_id ) = @_;
1298
1299         warn "Retreiveing copy copy counts for record $record_id and method " . $self->api_name . "\n";
1300
1301         my $method = "open-ils.storage.biblio.record_entry.global_copy_count.atomic";
1302         if($self->api_name =~ /staff/) { $method =~ s/atomic/staff\.atomic/; }
1303
1304         my $counts = $apputils->simple_scalar_request(
1305                 "open-ils.storage", $method, $record_id );
1306
1307         $counts = [ sort {$a->[0] <=> $b->[0]} @$counts ];
1308         return $counts;
1309 }
1310
1311
1312 __PACKAGE__->register_method(
1313         method          => "copy_count_summary",
1314         api_name        => "open-ils.search.biblio.copy_counts.summary.retrieve",
1315         notes           => <<"  NOTES");
1316         returns an array of these:
1317                 [ org_id, callnumber_label, <status1_count>, <status2_cout>,...]
1318                 where statusx is a copy status name.  the statuses are sorted
1319                 by id.
1320         NOTES
1321
1322 sub copy_count_summary {
1323         my( $self, $client, $rid, $org, $depth ) = @_;
1324         $org ||= 1;
1325         $depth ||= 0;
1326     my $data = $U->storagereq(
1327                 'open-ils.storage.biblio.record_entry.status_copy_count.atomic', $rid, $org, $depth );
1328
1329     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1330 }
1331
1332 __PACKAGE__->register_method(
1333         method          => "copy_location_count_summary",
1334         api_name        => "open-ils.search.biblio.copy_location_counts.summary.retrieve",
1335         notes           => <<"  NOTES");
1336         returns an array of these:
1337                 [ org_id, callnumber_label, copy_location, <status1_count>, <status2_cout>,...]
1338                 where statusx is a copy status name.  the statuses are sorted
1339                 by id.
1340         NOTES
1341
1342 sub copy_location_count_summary {
1343         my( $self, $client, $rid, $org, $depth ) = @_;
1344         $org ||= 1;
1345         $depth ||= 0;
1346     my $data = $U->storagereq(
1347                 'open-ils.storage.biblio.record_entry.status_copy_location_count.atomic', $rid, $org, $depth );
1348
1349     return [ sort { $a->[1] cmp $b->[1] || $a->[2] cmp $b->[2] } @$data ];
1350 }
1351
1352 __PACKAGE__->register_method(
1353         method          => "copy_count_location_summary",
1354         api_name        => "open-ils.search.biblio.copy_counts.location.summary.retrieve",
1355         notes           => <<"  NOTES");
1356         returns an array of these:
1357                 [ org_id, callnumber_label, <status1_count>, <status2_cout>,...]
1358                 where statusx is a copy status name.  the statuses are sorted
1359                 by id.
1360         NOTES
1361
1362 sub copy_count_location_summary {
1363         my( $self, $client, $rid, $org, $depth ) = @_;
1364         $org ||= 1;
1365         $depth ||= 0;
1366     my $data = $U->storagereq(
1367         'open-ils.storage.biblio.record_entry.status_copy_location_count.atomic', $rid, $org, $depth );
1368     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1369 }
1370
1371
1372 __PACKAGE__->register_method(
1373         method          => "marc_search",
1374         api_name        => "open-ils.search.biblio.marc.staff");
1375
1376 __PACKAGE__->register_method(
1377         method          => "marc_search",
1378         api_name        => "open-ils.search.biblio.marc",
1379         notes           => <<"  NOTES");
1380                 Example:
1381                 open-ils.storage.biblio.full_rec.multi_search.atomic 
1382                 { "searches": [{"term":"harry","restrict": [{"tag":245,"subfield":"a"}]}], "org_unit": 1,
1383         "limit":5,"sort":"author","item_type":"g"}
1384         NOTES
1385
1386 sub marc_search {
1387         my( $self, $conn, $args, $limit, $offset ) = @_;
1388
1389         my $method = 'open-ils.storage.biblio.full_rec.multi_search';
1390         $method .= ".staff" if $self->api_name =~ /staff/;
1391         $method .= ".atomic";
1392
1393         $limit ||= 10;
1394         $offset ||= 0;
1395
1396         my @search;
1397         push( @search, ($_ => $$args{$_}) ) for (sort keys %$args);
1398         my $ckey = $pfx . md5_hex($method . OpenSRF::Utils::JSON->perl2JSON(\@search));
1399
1400         my $recs = search_cache($ckey, $offset, $limit);
1401
1402         if(!$recs) {
1403                 $recs = $U->storagereq($method, %$args) || [];
1404                 if( $recs ) {
1405                         put_cache($ckey, scalar(@$recs), $recs);
1406                         $recs = [ @$recs[$offset..($offset + ($limit - 1))] ];
1407                 } else {
1408                         $recs = [];
1409                 }
1410         }
1411
1412         my $count = 0;
1413         $count = $recs->[0]->[2] if $recs->[0] and $recs->[0]->[2];
1414         my @recs = map { $_->[0] } @$recs;
1415
1416         return { ids => \@recs, count => $count };
1417 }
1418
1419
1420 __PACKAGE__->register_method(
1421         method  => "biblio_search_isbn",
1422         api_name        => "open-ils.search.biblio.isbn",
1423 );
1424
1425 sub biblio_search_isbn { 
1426         my( $self, $client, $isbn ) = @_;
1427         $logger->debug("Searching ISBN $isbn");
1428         my $e = new_editor();
1429         my $recs = $U->storagereq(
1430                 'open-ils.storage.id_list.biblio.record_entry.search.isbn.atomic', $isbn );
1431         return { ids => $recs, count => scalar(@$recs) };
1432 }
1433
1434
1435 __PACKAGE__->register_method(
1436         method  => "biblio_search_issn",
1437         api_name        => "open-ils.search.biblio.issn",
1438 );
1439
1440 sub biblio_search_issn { 
1441         my( $self, $client, $issn ) = @_;
1442         $logger->debug("Searching ISSN $issn");
1443         my $e = new_editor();
1444         $issn =~ s/-/ /g;
1445         my $recs = $U->storagereq(
1446                 'open-ils.storage.id_list.biblio.record_entry.search.issn.atomic', $issn );
1447         return { ids => $recs, count => scalar(@$recs) };
1448 }
1449
1450
1451
1452
1453 __PACKAGE__->register_method(
1454         method  => "fetch_mods_by_copy",
1455         api_name        => "open-ils.search.biblio.mods_from_copy",
1456 );
1457
1458 sub fetch_mods_by_copy {
1459         my( $self, $client, $copyid ) = @_;
1460         my ($record, $evt) = $apputils->fetch_record_by_copy( $copyid );
1461         return $evt if $evt;
1462         return OpenILS::Event->new('ITEM_NOT_CATALOGED') unless $record->marc;
1463         return $apputils->record_to_mvr($record);
1464 }
1465
1466
1467
1468 # -------------------------------------------------------------------------------------
1469
1470 __PACKAGE__->register_method(
1471         method  => "cn_browse",
1472         api_name        => "open-ils.search.callnumber.browse.target",
1473         notes           => "Starts a callnumber browse"
1474         );
1475
1476 __PACKAGE__->register_method(
1477         method  => "cn_browse",
1478         api_name        => "open-ils.search.callnumber.browse.page_up",
1479         notes           => "Returns the previous page of callnumbers", 
1480         );
1481
1482 __PACKAGE__->register_method(
1483         method  => "cn_browse",
1484         api_name        => "open-ils.search.callnumber.browse.page_down",
1485         notes           => "Returns the next page of callnumbers", 
1486         );
1487
1488
1489 # RETURNS array of arrays like so: label, owning_lib, record, id
1490 sub cn_browse {
1491         my( $self, $client, @params ) = @_;
1492         my $method;
1493
1494         $method = 'open-ils.storage.asset.call_number.browse.target.atomic' 
1495                 if( $self->api_name =~ /target/ );
1496         $method = 'open-ils.storage.asset.call_number.browse.page_up.atomic'
1497                 if( $self->api_name =~ /page_up/ );
1498         $method = 'open-ils.storage.asset.call_number.browse.page_down.atomic'
1499                 if( $self->api_name =~ /page_down/ );
1500
1501         return $apputils->simplereq( 'open-ils.storage', $method, @params );
1502 }
1503 # -------------------------------------------------------------------------------------
1504
1505 __PACKAGE__->register_method(
1506         method => "fetch_cn",
1507     authoritative => 1,
1508         api_name => "open-ils.search.callnumber.retrieve",
1509         notes           => "retrieves a callnumber based on ID",
1510         );
1511
1512 sub fetch_cn {
1513         my( $self, $client, $id ) = @_;
1514         my( $cn, $evt ) = $apputils->fetch_callnumber( $id );
1515         return $evt if $evt;
1516         return $cn;
1517 }
1518
1519 __PACKAGE__->register_method (
1520         method          => "fetch_copy_by_cn",
1521         api_name                => 'open-ils.search.copies_by_call_number.retrieve',
1522         signature       => q/
1523                 Returns an array of copy id's by callnumber id
1524                 @param cnid The callnumber id
1525                 @return An array of copy ids
1526         /
1527 );
1528
1529 sub fetch_copy_by_cn {
1530         my( $self, $conn, $cnid ) = @_;
1531         return $U->cstorereq(
1532                 'open-ils.cstore.direct.asset.copy.id_list.atomic', 
1533                 { call_number => $cnid, deleted => 'f' } );
1534 }
1535
1536 __PACKAGE__->register_method (
1537         method          => 'fetch_cn_by_info',
1538         api_name                => 'open-ils.search.call_number.retrieve_by_info',
1539         signature       => q/
1540                 @param label The callnumber label
1541                 @param record The record the cn is attached to
1542                 @param org The owning library of the cn
1543                 @return The callnumber object
1544         /
1545 );
1546
1547
1548 sub fetch_cn_by_info {
1549         my( $self, $conn, $label, $record, $org ) = @_;
1550         return $U->cstorereq(
1551                 'open-ils.cstore.direct.asset.call_number.search',
1552                 { label => $label, record => $record, owning_lib => $org, deleted => 'f' });
1553 }
1554
1555
1556                 
1557
1558
1559 __PACKAGE__->register_method (
1560         method => 'bib_extras',
1561         api_name => 'open-ils.search.biblio.lit_form_map.retrieve.all');
1562 __PACKAGE__->register_method (
1563         method => 'bib_extras',
1564         api_name => 'open-ils.search.biblio.item_form_map.retrieve.all');
1565 __PACKAGE__->register_method (
1566         method => 'bib_extras',
1567         api_name => 'open-ils.search.biblio.item_type_map.retrieve.all');
1568 __PACKAGE__->register_method (
1569         method => 'bib_extras',
1570         api_name => 'open-ils.search.biblio.bib_level_map.retrieve.all');
1571 __PACKAGE__->register_method (
1572         method => 'bib_extras',
1573         api_name => 'open-ils.search.biblio.audience_map.retrieve.all');
1574
1575 sub bib_extras {
1576         my $self = shift;
1577
1578         my $e = new_editor();
1579
1580         return $e->retrieve_all_config_lit_form_map()
1581                 if( $self->api_name =~ /lit_form/ );
1582
1583         return $e->retrieve_all_config_item_form_map()
1584                 if( $self->api_name =~ /item_form_map/ );
1585
1586         return $e->retrieve_all_config_item_type_map()
1587                 if( $self->api_name =~ /item_type_map/ );
1588
1589         return $e->retrieve_all_config_bib_level_map()
1590                 if( $self->api_name =~ /bib_level_map/ );
1591
1592         return $e->retrieve_all_config_audience_map()
1593                 if( $self->api_name =~ /audience_map/ );
1594
1595         return [];
1596 }
1597
1598
1599
1600 __PACKAGE__->register_method(
1601         method  => 'fetch_slim_record',
1602         api_name        => 'open-ils.search.biblio.record_entry.slim.retrieve',
1603         signature=> q/
1604                 Returns a biblio.record_entry without the attached marcxml
1605         /
1606 );
1607
1608 sub fetch_slim_record {
1609         my( $self, $conn, $ids ) = @_;
1610
1611         #my $editor = OpenILS::Utils::Editor->new;
1612         my $editor = new_editor();
1613         my @res;
1614         for( @$ids ) {
1615                 return $editor->event unless
1616                         my $r = $editor->retrieve_biblio_record_entry($_);
1617                 $r->clear_marc;
1618                 push(@res, $r);
1619         }
1620         return \@res;
1621 }
1622
1623
1624
1625 __PACKAGE__->register_method(
1626         method => 'rec_to_mr_rec_descriptors',
1627         api_name        => 'open-ils.search.metabib.record_to_descriptors',
1628         signature       => q/
1629                 specialized method...
1630                 Given a biblio record id or a metarecord id, 
1631                 this returns a list of metabib.record_descriptor
1632                 objects that live within the same metarecord
1633                 @param args Object of args including:
1634         /
1635 );
1636
1637 sub rec_to_mr_rec_descriptors {
1638         my( $self, $conn, $args ) = @_;
1639
1640         my $rec = $$args{record};
1641         my $mrec        = $$args{metarecord};
1642         my $item_forms = $$args{item_forms};
1643         my $item_types  = $$args{item_types};
1644         my $item_lang   = $$args{item_lang};
1645
1646         my $e = new_editor();
1647         my $recs;
1648
1649         if( !$mrec ) {
1650                 my $map = $e->search_metabib_metarecord_source_map({source => $rec});
1651                 return $e->event unless @$map;
1652                 $mrec = $$map[0]->metarecord;
1653         }
1654
1655         $recs = $e->search_metabib_metarecord_source_map({metarecord => $mrec});
1656         return $e->event unless @$recs;
1657
1658         my @recs = map { $_->source } @$recs;
1659         my $search = { record => \@recs };
1660         $search->{item_form} = $item_forms if $item_forms and @$item_forms;
1661         $search->{item_type} = $item_types if $item_types and @$item_types;
1662         $search->{item_lang} = $item_lang if $item_lang;
1663
1664         my $desc = $e->search_metabib_record_descriptor($search);
1665
1666         return { metarecord => $mrec, descriptors => $desc };
1667 }
1668
1669
1670
1671
1672 __PACKAGE__->register_method(
1673         method => 'copies_created_on',  
1674 );
1675
1676
1677 sub copies_created_on {
1678         my( $self, $conn, $auth, $org, $date ) = @_;
1679         my $e = new_editor(authtoken=>$auth);
1680         return $e->event unless $e->checkauth;
1681 }
1682
1683
1684 __PACKAGE__->register_method(
1685         method => 'fetch_age_protect',
1686         api_name => 'open-ils.search.copy.age_protect.retrieve.all',
1687 );
1688
1689 sub fetch_age_protect {
1690         return new_editor()->retrieve_all_config_rule_age_hold_protect();
1691 }
1692
1693
1694 __PACKAGE__->register_method(
1695         method => 'copies_by_cn_label',
1696         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label',
1697 );
1698
1699 __PACKAGE__->register_method(
1700         method => 'copies_by_cn_label',
1701         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label.staff',
1702 );
1703
1704 sub copies_by_cn_label {
1705         my( $self, $conn, $record, $label, $circ_lib ) = @_;
1706         my $e = new_editor();
1707         my $cns = $e->search_asset_call_number({record => $record, label => $label, deleted => 'f'}, {idlist=>1});
1708         return [] unless @$cns;
1709
1710         # show all non-deleted copies in the staff client ...
1711         if ($self->api_name =~ /staff$/o) {
1712                 return $e->search_asset_copy({call_number => $cns, circ_lib => $circ_lib, deleted => 'f'}, {idlist=>1});
1713         }
1714
1715         # ... otherwise, grab the copies ...
1716         my $copies = $e->search_asset_copy(
1717                 [ {call_number => $cns, circ_lib => $circ_lib, deleted => 'f', opac_visible => 't'},
1718                   {flesh => 1, flesh_fields => { acp => [ qw/location status/] } }
1719                 ]
1720         );
1721
1722         # ... and test for location and status visibility
1723         return [ map { ($U->is_true($_->location->opac_visible) && $U->is_true($_->status->opac_visible)) ? ($_->id) : () } @$copies ];
1724 }
1725
1726
1727
1728 1;
1729
1730