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