]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/SuperCat.pm
order_by update
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / SuperCat.pm
1 package OpenILS::Application::SuperCat;
2
3 use strict;
4 use warnings;
5
6 # All OpenSRF applications must be based on OpenSRF::Application or
7 # a subclass thereof.  Makes sense, eh?
8 use OpenSRF::Application;
9 use base qw/OpenSRF::Application/;
10
11 # This is the client class, used for connecting to open-ils.storage
12 use OpenSRF::AppSession;
13
14 # This is an extention of Error.pm that supplies some error types to throw
15 use OpenSRF::EX qw(:try);
16
17 # This is a helper class for querying the OpenSRF Settings application ...
18 use OpenSRF::Utils::SettingsClient;
19
20 # ... and here we have the built in logging helper ...
21 use OpenSRF::Utils::Logger qw($logger);
22
23 # ... and this is our OpenILS object (en|de)coder and psuedo-ORM package.
24 use OpenILS::Utils::Fieldmapper;
25
26
27 # We'll be working with XML, so...
28 use XML::LibXML;
29 use XML::LibXSLT;
30 use Unicode::Normalize;
31
32 use JSON;
33
34 our (
35   $_parser,
36   $_xslt,
37   %record_xslt,
38   %metarecord_xslt,
39   %holdings_data_cache,
40 );
41
42 sub child_init {
43         # we need an XML parser
44         $_parser = new XML::LibXML;
45
46         # and an xslt parser
47         $_xslt = new XML::LibXSLT;
48         
49         # parse the MODS xslt ...
50         my $mods3_xslt = $_parser->parse_file(
51                 OpenSRF::Utils::SettingsClient
52                         ->new
53                         ->config_value( dirs => 'xsl' ).
54                 "/MARC21slim2MODS3.xsl"
55         );
56         # and stash a transformer
57         $record_xslt{mods3}{xslt} = $_xslt->parse_stylesheet( $mods3_xslt );
58         $record_xslt{mods3}{namespace_uri} = 'http://www.loc.gov/mods/v3';
59         $record_xslt{mods3}{docs} = 'http://www.loc.gov/mods/';
60         $record_xslt{mods3}{schema_location} = 'http://www.loc.gov/standards/mods/v3/mods-3-1.xsd';
61
62         # parse the MODS xslt ...
63         my $mods_xslt = $_parser->parse_file(
64                 OpenSRF::Utils::SettingsClient
65                         ->new
66                         ->config_value( dirs => 'xsl' ).
67                 "/MARC21slim2MODS.xsl"
68         );
69         # and stash a transformer
70         $record_xslt{mods}{xslt} = $_xslt->parse_stylesheet( $mods_xslt );
71         $record_xslt{mods}{namespace_uri} = 'http://www.loc.gov/mods/';
72         $record_xslt{mods}{docs} = 'http://www.loc.gov/mods/';
73         $record_xslt{mods}{schema_location} = 'http://www.loc.gov/standards/mods/mods.xsd';
74
75         # parse the ATOM entry xslt ...
76         my $atom_xslt = $_parser->parse_file(
77                 OpenSRF::Utils::SettingsClient
78                         ->new
79                         ->config_value( dirs => 'xsl' ).
80                 "/MARC21slim2ATOM.xsl"
81         );
82         # and stash a transformer
83         $record_xslt{atom}{xslt} = $_xslt->parse_stylesheet( $atom_xslt );
84         $record_xslt{atom}{namespace_uri} = 'http://www.w3.org/2005/Atom';
85         $record_xslt{atom}{docs} = 'http://www.ietf.org/rfc/rfc4287.txt';
86
87         # parse the RDFDC xslt ...
88         my $rdf_dc_xslt = $_parser->parse_file(
89                 OpenSRF::Utils::SettingsClient
90                         ->new
91                         ->config_value( dirs => 'xsl' ).
92                 "/MARC21slim2RDFDC.xsl"
93         );
94         # and stash a transformer
95         $record_xslt{rdf_dc}{xslt} = $_xslt->parse_stylesheet( $rdf_dc_xslt );
96         $record_xslt{rdf_dc}{namespace_uri} = 'http://purl.org/dc/elements/1.1/';
97         $record_xslt{rdf_dc}{schema_location} = 'http://purl.org/dc/elements/1.1/';
98
99         # parse the SRWDC xslt ...
100         my $srw_dc_xslt = $_parser->parse_file(
101                 OpenSRF::Utils::SettingsClient
102                         ->new
103                         ->config_value( dirs => 'xsl' ).
104                 "/MARC21slim2SRWDC.xsl"
105         );
106         # and stash a transformer
107         $record_xslt{srw_dc}{xslt} = $_xslt->parse_stylesheet( $srw_dc_xslt );
108         $record_xslt{srw_dc}{namespace_uri} = 'info:srw/schema/1/dc-schema';
109         $record_xslt{srw_dc}{schema_location} = 'http://www.loc.gov/z3950/agency/zing/srw/dc-schema.xsd';
110
111         # parse the OAIDC xslt ...
112         my $oai_dc_xslt = $_parser->parse_file(
113                 OpenSRF::Utils::SettingsClient
114                         ->new
115                         ->config_value( dirs => 'xsl' ).
116                 "/MARC21slim2OAIDC.xsl"
117         );
118         # and stash a transformer
119         $record_xslt{oai_dc}{xslt} = $_xslt->parse_stylesheet( $oai_dc_xslt );
120         $record_xslt{oai_dc}{namespace_uri} = 'http://www.openarchives.org/OAI/2.0/oai_dc/';
121         $record_xslt{oai_dc}{schema_location} = 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd';
122
123         # parse the RSS xslt ...
124         my $rss_xslt = $_parser->parse_file(
125                 OpenSRF::Utils::SettingsClient
126                         ->new
127                         ->config_value( dirs => 'xsl' ).
128                 "/MARC21slim2RSS2.xsl"
129         );
130         # and stash a transformer
131         $record_xslt{rss2}{xslt} = $_xslt->parse_stylesheet( $rss_xslt );
132
133         register_record_transforms();
134
135         return 1;
136 }
137
138 sub register_record_transforms {
139         for my $type ( keys %record_xslt ) {
140                 __PACKAGE__->register_method(
141                         method    => 'retrieve_record_transform',
142                         api_name  => "open-ils.supercat.record.$type.retrieve",
143                         api_level => 1,
144                         argc      => 1,
145                         signature =>
146                                 { desc     => "Returns the \U$type\E representation ".
147                                               "of the requested bibliographic record",
148                                   params   =>
149                                         [
150                                                 { name => 'bibId',
151                                                   desc => 'An OpenILS biblio::record_entry id',
152                                                   type => 'number' },
153                                         ],
154                                 'return' =>
155                                         { desc => "The bib record in \U$type\E",
156                                           type => 'string' }
157                                 }
158                 );
159
160                 __PACKAGE__->register_method(
161                         method    => 'retrieve_isbn_transform',
162                         api_name  => "open-ils.supercat.isbn.$type.retrieve",
163                         api_level => 1,
164                         argc      => 1,
165                         signature =>
166                                 { desc     => "Returns the \U$type\E representation ".
167                                               "of the requested bibliographic record",
168                                   params   =>
169                                         [
170                                                 { name => 'isbn',
171                                                   desc => 'An ISBN',
172                                                   type => 'string' },
173                                         ],
174                                 'return' =>
175                                         { desc => "The bib record in \U$type\E",
176                                           type => 'string' }
177                                 }
178                 );
179         }
180 }
181
182
183 sub entityize {
184         my $stuff = NFC(shift());
185         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
186         return $stuff;
187 }
188
189 sub tree_walker {
190         my $tree = shift;
191         my $field = shift;
192         my $filter = shift;
193
194         return unless ($tree && ref($tree->$field));
195
196         my @things = $filter->($tree);
197         for my $v ( @{$tree->$field} ){
198                 push @things, $filter->($v);
199                 push @things, tree_walker($v, $field, $filter);
200         }
201         return @things
202 }
203
204 sub cn_browse {
205         my $self = shift;
206         my $client = shift;
207
208         my $label = shift;
209         my $ou = shift;
210         my $page_size = shift || 9;
211         my $page = shift || 0;
212
213         my ($before_limit,$after_limit) = (0,0);
214         my ($before_offset,$after_offset) = (0,0);
215
216         if (!$page) {
217                 $before_limit = $after_limit = int($page_size / 2);
218                 $after_limit += 1 if ($page_size % 2);
219         } else {
220                 $before_offset = $after_offset = int($page_size / 2);
221                 $before_offset += 1 if ($page_size % 2);
222                 $before_limit = $after_limit = $page_size;
223         }
224
225         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
226
227         my $o_search = { shortname => $ou };
228         if (!$ou || $ou eq '-') {
229                 $o_search = { parent_ou => undef };
230         }
231
232         my $orgs = $_storage->request(
233                 "open-ils.cstore.direct.actor.org_unit.search",
234                 $o_search,
235                 { flesh         => 3,
236                   flesh_fields  => { aou        => [qw/children/] }
237                 }
238         )->gather(1);
239
240         my @ou_ids = tree_walker($orgs, 'children', sub {shift->id}) if $orgs;
241
242         $logger->debug("Searching for CNs at orgs [".join(',',@ou_ids)."], based on $ou");
243
244         my @list = ();
245
246         if ($page <= 0) {
247                 my $before = $_storage->request(
248                         "open-ils.cstore.direct.asset.call_number.search.atomic",
249                         { label         => { "<" => { transform => "upper", value => ["upper", $label] } },
250                           owning_lib    => \@ou_ids,
251                         },
252                         { flesh         => 1,
253                           flesh_fields  => { acn => [qw/record owning_lib/] },
254                           order_by      => { acn => "upper(label) desc, id desc, owning_lib desc" },
255                           limit         => $before_limit,
256                           offset        => abs($page) * $page_size - $before_offset,
257                         }
258                 )->gather(1);
259                 push @list, reverse(@$before);
260         }
261
262         if ($page >= 0) {
263                 my $after = $_storage->request(
264                         "open-ils.cstore.direct.asset.call_number.search.atomic",
265                         { label         => { ">=" => { transform => "upper", value => ["upper", $label] } },
266                           owning_lib    => \@ou_ids,
267                         },
268                         { flesh         => 1,
269                           flesh_fields  => { acn => [qw/record owning_lib/] },
270                           order_by      => { acn => "upper(label), id, owning_lib" },
271                           limit         => $after_limit,
272                           offset        => abs($page) * $page_size - $after_offset,
273                         }
274                 )->gather(1);
275                 push @list, @$after;
276         }
277
278         return \@list;
279 }
280 __PACKAGE__->register_method(
281         method    => 'cn_browse',
282         api_name  => 'open-ils.supercat.call_number.browse',
283         api_level => 1,
284         argc      => 1,
285         signature =>
286                 { desc     => <<"                 DESC",
287 Returns the XML representation of the requested bibliographic record's holdings
288                   DESC
289                   params   =>
290                         [
291                                 { name => 'label',
292                                   desc => 'The target call number lable',
293                                   type => 'string' },
294                                 { name => 'org_unit',
295                                   desc => 'The org unit shortname (or "-" or undef for global) to browse',
296                                   type => 'string' },
297                                 { name => 'page_size',
298                                   desc => 'Count of call numbers to retrieve, default is 9',
299                                   type => 'number' },
300                                 { name => 'page',
301                                   desc => 'The page of call numbers to retrieve, calculated based on page_size.  Can be positive, negative or 0.',
302                                   type => 'number' },
303                         ],
304                   'return' =>
305                         { desc => 'Call numbers with owning_lib and record fleshed',
306                           type => 'array' }
307                 }
308 );
309
310
311 sub new_record_holdings {
312         my $self = shift;
313         my $client = shift;
314         my $bib = shift;
315         my $ou = shift;
316
317         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
318
319         my $tree = $_storage->request(
320                 "open-ils.cstore.direct.biblio.record_entry.retrieve",
321                 $bib,
322                 { flesh         => 5,
323                   flesh_fields  => {
324                                         bre     => [qw/call_numbers/],
325                                         acn     => [qw/copies owning_lib/],
326                                         acp     => [qw/location status circ_lib stat_cat_entries notes/],
327                                         asce    => [qw/stat_cat/],
328                                 }
329                 }
330         )->gather(1);
331
332         my $o_search = { shortname => uc($ou) };
333         if (!$ou || $ou eq '-') {
334                 $o_search = { parent_ou => undef };
335         }
336
337         my $orgs = $_storage->request(
338                 "open-ils.cstore.direct.actor.org_unit.search",
339                 $o_search,
340                 { flesh         => 3,
341                   flesh_fields  => { aou        => [qw/children/] }
342                 }
343         )->gather(1);
344
345         my @ou_ids = tree_walker($orgs, 'children', sub {shift->id}) if $orgs;
346
347         $logger->debug("Searching for holdings at orgs [".join(',',@ou_ids)."], based on $ou");
348
349         my ($year,$month,$day) = reverse( (localtime)[3,4,5] );
350         $year += 1900;
351         $month += 1;
352
353         my $xml = "<hold:volumes xmlns:hold='http://open-ils.org/spec/holdings/v1'>";
354
355         for my $cn (@{$tree->call_numbers}) {
356
357                 my $found = 0;
358                 for my $c (@{$cn->copies}) {
359                         next unless grep {$c->circ_lib->id == $_} @ou_ids;
360                         $found = 1;
361                 }
362                 next unless $found;
363
364                 (my $cn_class = $cn->class_name) =~ s/::/-/gso;
365                 $cn_class =~ s/Fieldmapper-//gso;
366                 my $cn_tag = sprintf("tag:open-ils.org,$year-\%0.2d-\%0.2d:$cn_class/".$cn->id, $month, $day);
367
368                 my $cn_lib = $cn->owning_lib->shortname;
369
370                 my $cn_label = $cn->label;
371
372                 $xml .= "<hold:volume id='$cn_tag' lib='$cn_lib' label='$cn_label'><hold:copies>";
373                 
374                 for my $cp (@{$cn->copies}) {
375
376                         next unless grep { $cp->circ_lib->id == $_ } @ou_ids;
377
378                         (my $cp_class = $cp->class_name) =~ s/::/-/gso;
379                         $cp_class =~ s/Fieldmapper-//gso;
380                         my $cp_tag = sprintf("tag:open-ils.org,$year-\%0.2d-\%0.2d:$cp_class/".$cp->id, $month, $day);
381
382                         my $cp_stat = $cp->status->name;
383
384                         my $cp_loc = $cp->location->name;
385
386                         my $cp_lib = $cp->circ_lib->shortname;
387
388                         my $cp_bc = $cp->barcode;
389
390                         $xml .= "<hold:copy id='$cp_tag' barcode='$cp_bc'><hold:status>$cp_stat</hold:status>".
391                                 "<hold:location>$cp_loc</hold:location><hold:circlib>$cp_lib</hold:circlib><hold:notes>";
392
393                         #if ($cp->notes) {
394                         #       for my $note ( @{$cp->notes} ) {
395                         #               next unless ( $sce->stat_cat->pub eq 't' );
396                         #               $xml .= sprintf('<hold:note date="%s" title="%s">%s</hold:note>',$note->create_date, escape($note->title), escape($note->value));
397                         #       }
398                         #}
399
400                         $xml .= "</hold:notes><hold:statcats>";
401
402                         if ($cp->stat_cat_entries) {
403                                 for my $sce ( @{$cp->stat_cat_entries} ) {
404                                         next unless ( $sce->stat_cat->opac_visible eq 't' );
405                                         $xml .= sprintf('<hold:statcat name="%s">%s</hold:statcat>',escape($sce->stat_cat->name) ,escape($sce->value));
406                                 }
407                         }
408
409                         $xml .= "</hold:statcats></hold:copy>";
410                 }
411                 
412                 $xml .= "</hold:copies></hold:volume>";
413         }
414
415         $xml .= "</hold:volumes>";
416
417         return $xml;
418 }
419 __PACKAGE__->register_method(
420         method    => 'new_record_holdings',
421         api_name  => 'open-ils.supercat.record.holdings_xml.retrieve',
422         api_level => 1,
423         argc      => 1,
424         signature =>
425                 { desc     => <<"                 DESC",
426 Returns the XML representation of the requested bibliographic record's holdings
427                   DESC
428                   params   =>
429                         [
430                                 { name => 'bibId',
431                                   desc => 'An OpenILS biblio::record_entry id',
432                                   type => 'number' },
433                         ],
434                   'return' =>
435                         { desc => 'The bib record holdings hierarchy in XML',
436                           type => 'string' }
437                 }
438 );
439
440 sub isbn_holdings {
441         my $self = shift;
442         my $client = shift;
443         my $isbn = shift;
444
445         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
446
447         my $recs = $_storage->request(
448                         'open-ils.cstore.direct.metabib.full_rec.search.atomic',
449                         { tag => { like => '02%'}, value => {like => "$isbn\%"}}
450         )->gather(1);
451
452         return undef unless (@$recs);
453
454         return ($self->method_lookup( 'open-ils.supercat.record.holdings_xml.retrieve')->run( $recs->[0]->record ))[0];
455 }
456 __PACKAGE__->register_method(
457         method    => 'isbn_holdings',
458         api_name  => 'open-ils.supercat.isbn.holdings_xml.retrieve',
459         api_level => 1,
460         argc      => 1,
461         signature =>
462                 { desc     => <<"                 DESC",
463 Returns the XML representation of the requested bibliographic record's holdings
464                   DESC
465                   params   =>
466                         [
467                                 { name => 'isbn',
468                                   desc => 'An isbn',
469                                   type => 'string' },
470                         ],
471                   'return' =>
472                         { desc => 'The bib record holdings hierarchy in XML',
473                           type => 'string' }
474                 }
475 );
476
477 sub escape {
478         my $text = shift;
479         $text =~ s/&/&amp;/gsom;
480         $text =~ s/</&lt;/gsom;
481         $text =~ s/>/&gt;/gsom;
482         $text =~ s/"/\\"/gsom;
483         return $text;
484 }
485
486 sub recent_changes {
487         my $self = shift;
488         my $client = shift;
489         my $when = shift || '1-01-01';
490         my $limit = shift;
491
492         my $type = 'biblio';
493         $type = 'authority' if ($self->api_name =~ /authority/o);
494
495         my $axis = 'create_date';
496         $axis = 'edit_date' if ($self->api_name =~ /edit/o);
497
498         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
499
500         return $_storage->request(
501                 "open-ils.cstore.direct.$type.record_entry.id_list.atomic",
502                 { $axis => { ">" => $when }, id => { '>' => 0 } },
503                 { order_by => { bre => "$axis desc" }, limit => $limit }
504         )->gather(1);
505 }
506
507 for my $t ( qw/biblio authority/ ) {
508         for my $a ( qw/import edit/ ) {
509
510                 __PACKAGE__->register_method(
511                         method    => 'recent_changes',
512                         api_name  => "open-ils.supercat.$t.record.$a.recent",
513                         api_level => 1,
514                         argc      => 0,
515                         signature =>
516                                 { desc     => "Returns a list of recently ${a}ed $t records",
517                                   params   =>
518                                         [
519                                                 { name => 'when',
520                                                   desc => "Date to start looking for ${a}ed records",
521                                                   default => '1-01-01',
522                                                   type => 'string' },
523
524                                                 { name => 'limit',
525                                                   desc => "Maximum count to retrieve",
526                                                   type => 'number' },
527                                         ],
528                                   'return' =>
529                                         { desc => "An id list of $t records",
530                                           type => 'array' }
531                                 },
532                 );
533         }
534 }
535
536
537 sub retrieve_record_marcxml {
538         my $self = shift;
539         my $client = shift;
540         my $rid = shift;
541
542         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
543
544         my $record = $_storage->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $rid )->gather(1);
545         return entityize( $record->marc ) if ($record);
546         return undef;
547 }
548
549 __PACKAGE__->register_method(
550         method    => 'retrieve_record_marcxml',
551         api_name  => 'open-ils.supercat.record.marcxml.retrieve',
552         api_level => 1,
553         argc      => 1,
554         signature =>
555                 { desc     => <<"                 DESC",
556 Returns the MARCXML representation of the requested bibliographic record
557                   DESC
558                   params   =>
559                         [
560                                 { name => 'bibId',
561                                   desc => 'An OpenILS biblio::record_entry id',
562                                   type => 'number' },
563                         ],
564                   'return' =>
565                         { desc => 'The bib record in MARCXML',
566                           type => 'string' }
567                 }
568 );
569
570 sub retrieve_isbn_marcxml {
571         my $self = shift;
572         my $client = shift;
573         my $isbn = shift;
574
575         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
576
577         my $recs = $_storage->request(
578                         'open-ils.cstore.direct.metabib.full_rec.search.atomic',
579                         { tag => { like => '02%'}, value => {like => "$isbn\%"}}
580         )->gather(1);
581
582         return undef unless (@$recs);
583
584         my $record = $_storage->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $recs->[0]->record )->gather(1);
585         return entityize( $record->marc ) if ($record);
586         return undef;
587 }
588
589 __PACKAGE__->register_method(
590         method    => 'retrieve_isbn_marcxml',
591         api_name  => 'open-ils.supercat.isbn.marcxml.retrieve',
592         api_level => 1,
593         argc      => 1,
594         signature =>
595                 { desc     => <<"                 DESC",
596 Returns the MARCXML representation of the requested ISBN
597                   DESC
598                   params   =>
599                         [
600                                 { name => 'ISBN',
601                                   desc => 'An ... um ... ISBN',
602                                   type => 'string' },
603                         ],
604                   'return' =>
605                         { desc => 'The bib record in MARCXML',
606                           type => 'string' }
607                 }
608 );
609
610 sub retrieve_record_transform {
611         my $self = shift;
612         my $client = shift;
613         my $rid = shift;
614
615         (my $transform = $self->api_name) =~ s/^.+record\.([^\.]+)\.retrieve$/$1/o;
616
617         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
618         $_storage->connect;
619
620         my $record = $_storage->request(
621                 'open-ils.cstore.direct.biblio.record_entry.retrieve',
622                 $rid
623         )->gather(1);
624
625         return undef unless ($record);
626
627         return entityize($record_xslt{$transform}{xslt}->transform( $_parser->parse_string( $record->marc ) )->toString);
628 }
629
630 sub retrieve_isbn_transform {
631         my $self = shift;
632         my $client = shift;
633         my $isbn = shift;
634
635         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
636
637         my $recs = $_storage->request(
638                         'open-ils.cstore.direct.metabib.full_rec.search.atomic',
639                         { tag => { like => '02%'}, value => {like => "$isbn\%"}}
640         )->gather(1);
641
642         return undef unless (@$recs);
643
644         (my $transform = $self->api_name) =~ s/^.+isbn\.([^\.]+)\.retrieve$/$1/o;
645
646         my $record = $_storage->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $recs->[0]->record )->gather(1);
647
648         return undef unless ($record);
649
650         return entityize($record_xslt{$transform}{xslt}->transform( $_parser->parse_string( $record->marc ) )->toString);
651 }
652
653 sub retrieve_record_objects {
654         my $self = shift;
655         my $client = shift;
656         my $ids = shift;
657
658         $ids = [$ids] unless (ref $ids);
659         $ids = [grep {$_} @$ids];
660
661         return [] unless (@$ids);
662
663         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
664         return $_storage->request('open-ils.cstore.direct.biblio.record_entry.search.atomic' => { id => [grep {$_} @$ids] })->gather(1);
665 }
666 __PACKAGE__->register_method(
667         method    => 'retrieve_record_objects',
668         api_name  => 'open-ils.supercat.record.object.retrieve',
669         api_level => 1,
670         argc      => 1,
671         signature =>
672                 { desc     => <<"                 DESC",
673 Returns the Fieldmapper object representation of the requested bibliographic records
674                   DESC
675                   params   =>
676                         [
677                                 { name => 'bibIds',
678                                   desc => 'OpenILS biblio::record_entry ids',
679                                   type => 'array' },
680                         ],
681                   'return' =>
682                         { desc => 'The bib records',
683                           type => 'array' }
684                 }
685 );
686
687
688 sub retrieve_isbn_object {
689         my $self = shift;
690         my $client = shift;
691         my $isbn = shift;
692
693         return undef unless ($isbn);
694
695         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
696         my $recs = $_storage->request(
697                         'open-ils.cstore.direct.metabib.full_rec.search.atomic',
698                         { tag => { like => '02%'}, value => {like => "$isbn\%"}}
699         )->gather(1);
700
701         return undef unless (@$recs);
702
703         return $_storage->request(
704                 'open-ils.cstore.direct.biblio.record_entry.search.atomic',
705                 { id => $recs->[0]->record }
706         )->gather(1);
707 }
708 __PACKAGE__->register_method(
709         method    => 'retrieve_isbn_object',
710         api_name  => 'open-ils.supercat.isbn.object.retrieve',
711         api_level => 1,
712         argc      => 1,
713         signature =>
714                 { desc     => <<"                 DESC",
715 Returns the Fieldmapper object representation of the requested bibliographic record
716                   DESC
717                   params   =>
718                         [
719                                 { name => 'isbn',
720                                   desc => 'an ISBN',
721                                   type => 'string' },
722                         ],
723                   'return' =>
724                         { desc => 'The bib record',
725                           type => 'object' }
726                 }
727 );
728
729
730
731 sub retrieve_metarecord_mods {
732         my $self = shift;
733         my $client = shift;
734         my $rid = shift;
735
736         my $_storage = OpenSRF::AppSession->connect( 'open-ils.cstore' );
737
738         # Get the metarecord in question
739         my $mr =
740         $_storage->request(
741                 'open-ils.cstore.direct.metabib.metarecord.retrieve' => $rid
742         )->gather(1);
743
744         # Now get the map of all bib records for the metarecord
745         my $recs =
746         $_storage->request(
747                 'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
748                 {metarecord => $rid}
749         )->gather(1);
750
751         $logger->debug("Adding ".scalar(@$recs)." bib record to the MODS of the metarecord");
752
753         # and retrieve the lead (master) record as MODS
754         my ($master) =
755                 $self   ->method_lookup('open-ils.supercat.record.mods.retrieve')
756                         ->run($mr->master_record);
757         my $master_mods = $_parser->parse_string($master)->documentElement;
758         $master_mods->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
759
760         # ... and a MODS clone to populate, with guts removed.
761         my $mods = $_parser->parse_string($master)->documentElement;
762         $mods->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
763         ($mods) = $mods->findnodes('//mods:mods');
764         $mods->removeChildNodes;
765
766         # Add the metarecord ID as a (locally defined) info URI
767         my $recordInfo = $mods
768                 ->ownerDocument
769                 ->createElement("mods:recordInfo");
770
771         my $recordIdentifier = $mods
772                 ->ownerDocument
773                 ->createElement("mods:recordIdentifier");
774
775         my ($year,$month,$day) = reverse( (localtime)[3,4,5] );
776         $year += 1900;
777         $month += 1;
778
779         my $id = $mr->id;
780         $recordIdentifier->appendTextNode(
781                 sprintf("tag:open-ils.org,$year-\%0.2d-\%0.2d:metabib-metarecord/$id", $month, $day)
782         );
783
784         $recordInfo->appendChild($recordIdentifier);
785         $mods->appendChild($recordInfo);
786
787         # Grab the title, author and ISBN for the master record and populate the metarecord
788         my ($title) = $master_mods->findnodes( './mods:titleInfo[not(@type)]' );
789         
790         if ($title) {
791                 $title->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
792                 $title = $mods->ownerDocument->importNode($title);
793                 $mods->appendChild($title);
794         }
795
796         my ($author) = $master_mods->findnodes( './mods:name[mods:role/mods:text[text()="creator"]]' );
797         if ($author) {
798                 $author->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
799                 $author = $mods->ownerDocument->importNode($author);
800                 $mods->appendChild($author);
801         }
802
803         my ($isbn) = $master_mods->findnodes( './mods:identifier[@type="isbn"]' );
804         if ($isbn) {
805                 $isbn->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
806                 $isbn = $mods->ownerDocument->importNode($isbn);
807                 $mods->appendChild($isbn);
808         }
809
810         # ... and loop over the constituent records
811         for my $map ( @$recs ) {
812
813                 # get the MODS
814                 my ($rec) =
815                         $self   ->method_lookup('open-ils.supercat.record.mods.retrieve')
816                                 ->run($map->source);
817
818                 my $part_mods = $_parser->parse_string($rec);
819                 $part_mods->documentElement->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
820                 ($part_mods) = $part_mods->findnodes('//mods:mods');
821
822                 for my $node ( ($part_mods->findnodes( './mods:subject' )) ) {
823                         $node->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
824                         $node = $mods->ownerDocument->importNode($node);
825                         $mods->appendChild( $node );
826                 }
827
828                 my $relatedItem = $mods
829                         ->ownerDocument
830                         ->createElement("mods:relatedItem");
831
832                 $relatedItem->setAttribute( type => 'constituent' );
833
834                 my $identifier = $mods
835                         ->ownerDocument
836                         ->createElement("mods:identifier");
837
838                 $identifier->setAttribute( type => 'uri' );
839
840                 my $subRecordInfo = $mods
841                         ->ownerDocument
842                         ->createElement("mods:recordInfo");
843
844                 my $subRecordIdentifier = $mods
845                         ->ownerDocument
846                         ->createElement("mods:recordIdentifier");
847
848                 my $subid = $map->source;
849                 $subRecordIdentifier->appendTextNode(
850                         sprintf("tag:open-ils.org,$year-\%0.2d-\%0.2d:biblio-record_entry/$subid",
851                                 $month,
852                                 $day
853                         )
854                 );
855                 $subRecordInfo->appendChild($subRecordIdentifier);
856
857                 $relatedItem->appendChild( $subRecordInfo );
858
859                 my ($tor) = $part_mods->findnodes( './mods:typeOfResource' );
860                 $tor->setNamespace( "http://www.loc.gov/mods/", "mods", 1 ) if ($tor);
861                 $tor = $mods->ownerDocument->importNode($tor) if ($tor);
862                 $relatedItem->appendChild($tor) if ($tor);
863
864                 if ( my ($part_isbn) = $part_mods->findnodes( './mods:identifier[@type="isbn"]' ) ) {
865                         $part_isbn->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
866                         $part_isbn = $mods->ownerDocument->importNode($part_isbn);
867                         $relatedItem->appendChild( $part_isbn );
868
869                         if (!$isbn) {
870                                 $isbn = $mods->appendChild( $part_isbn->cloneNode(1) );
871                         }
872                 }
873
874                 $mods->appendChild( $relatedItem );
875
876         }
877
878         $_storage->disconnect;
879
880         return entityize($mods->toString);
881
882 }
883 __PACKAGE__->register_method(
884         method    => 'retrieve_metarecord_mods',
885         api_name  => 'open-ils.supercat.metarecord.mods.retrieve',
886         api_level => 1,
887         argc      => 1,
888         signature =>
889                 { desc     => <<"                 DESC",
890 Returns the MODS representation of the requested metarecord
891                   DESC
892                   params   =>
893                         [
894                                 { name => 'metarecordId',
895                                   desc => 'An OpenILS metabib::metarecord id',
896                                   type => 'number' },
897                         ],
898                   'return' =>
899                         { desc => 'The metarecord in MODS',
900                           type => 'string' }
901                 }
902 );
903
904 sub list_metarecord_formats {
905         my @list = (
906                 { mods =>
907                         { namespace_uri   => 'http://www.loc.gov/mods/',
908                           docs            => 'http://www.loc.gov/mods/',
909                           schema_location => 'http://www.loc.gov/standards/mods/mods.xsd',
910                         }
911                 }
912         );
913
914         for my $type ( keys %metarecord_xslt ) {
915                 push @list,
916                         { $type => 
917                                 { namespace_uri   => $metarecord_xslt{$type}{namespace_uri},
918                                   docs            => $metarecord_xslt{$type}{docs},
919                                   schema_location => $metarecord_xslt{$type}{schema_location},
920                                 }
921                         };
922         }
923
924         return \@list;
925 }
926 __PACKAGE__->register_method(
927         method    => 'list_metarecord_formats',
928         api_name  => 'open-ils.supercat.metarecord.formats',
929         api_level => 1,
930         argc      => 0,
931         signature =>
932                 { desc     => <<"                 DESC",
933 Returns the list of valid metarecord formats that supercat understands.
934                   DESC
935                   'return' =>
936                         { desc => 'The format list',
937                           type => 'array' }
938                 }
939 );
940
941
942 sub list_record_formats {
943         my @list = (
944                 { marcxml =>
945                         { namespace_uri   => 'http://www.loc.gov/MARC21/slim',
946                           docs            => 'http://www.loc.gov/marcxml/',
947                           schema_location => 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd',
948                         }
949                 }
950         );
951
952         for my $type ( keys %record_xslt ) {
953                 push @list,
954                         { $type => 
955                                 { namespace_uri   => $record_xslt{$type}{namespace_uri},
956                                   docs            => $record_xslt{$type}{docs},
957                                   schema_location => $record_xslt{$type}{schema_location},
958                                 }
959                         };
960         }
961
962         return \@list;
963 }
964 __PACKAGE__->register_method(
965         method    => 'list_record_formats',
966         api_name  => 'open-ils.supercat.record.formats',
967         api_level => 1,
968         argc      => 0,
969         signature =>
970                 { desc     => <<"                 DESC",
971 Returns the list of valid record formats that supercat understands.
972                   DESC
973                   'return' =>
974                         { desc => 'The format list',
975                           type => 'array' }
976                 }
977 );
978 __PACKAGE__->register_method(
979         method    => 'list_record_formats',
980         api_name  => 'open-ils.supercat.isbn.formats',
981         api_level => 1,
982         argc      => 0,
983         signature =>
984                 { desc     => <<"                 DESC",
985 Returns the list of valid record formats that supercat understands.
986                   DESC
987                   'return' =>
988                         { desc => 'The format list',
989                           type => 'array' }
990                 }
991 );
992
993
994 sub oISBN {
995         my $self = shift;
996         my $client = shift;
997         my $isbn = shift;
998
999         throw OpenSRF::EX::InvalidArg ('I need an ISBN please')
1000                 unless (length($isbn) >= 10);
1001
1002         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
1003
1004         # Create a storage session, since we'll be making muliple requests.
1005         $_storage->connect;
1006
1007         # Find the record that has that ISBN.
1008         my $bibrec = $_storage->request(
1009                 'open-ils.cstore.direct.metabib.full_rec.search.atomic',
1010                 { tag => '020', subfield => 'a', value => { like => lc($isbn).'%'} }
1011         )->gather(1);
1012
1013         # Go away if we don't have one.
1014         return {} unless (@$bibrec);
1015
1016         # Find the metarecord for that bib record.
1017         my $mr = $_storage->request(
1018                 'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
1019                 {source => $bibrec->[0]->record}
1020         )->gather(1);
1021
1022         # Find the other records for that metarecord.
1023         my $records = $_storage->request(
1024                 'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
1025                 {metarecord => $mr->[0]->metarecord}
1026         )->gather(1);
1027
1028         # Just to be safe.  There's currently no unique constraint on sources...
1029         my %unique_recs = map { ($_->source, 1) } @$records;
1030         my @rec_list = sort keys %unique_recs;
1031
1032         # And now fetch the ISBNs for thos records.
1033         my $recs = [];
1034         push @$recs,
1035                 $_storage->request(
1036                         'open-ils.cstore.direct.metabib.full_rec.search',
1037                         { tag => '020', subfield => 'a', record => $_ }
1038                 )->gather(1) for (@rec_list);
1039
1040         # We're done with the storage server session.
1041         $_storage->disconnect;
1042
1043         # Return the oISBN data structure.  This will be XMLized at a higher layer.
1044         return
1045                 { metarecord => $mr->[0]->metarecord,
1046                   record_list => { map { ($_->record, $_->value) } @$recs } };
1047
1048 }
1049 __PACKAGE__->register_method(
1050         method    => 'oISBN',
1051         api_name  => 'open-ils.supercat.oisbn',
1052         api_level => 1,
1053         argc      => 1,
1054         signature =>
1055                 { desc     => <<"                 DESC",
1056 Returns the ISBN list for the metarecord of the requested isbn
1057                   DESC
1058                   params   =>
1059                         [
1060                                 { name => 'isbn',
1061                                   desc => 'An ISBN.  Duh.',
1062                                   type => 'string' },
1063                         ],
1064                   'return' =>
1065                         { desc => 'record to isbn map',
1066                           type => 'object' }
1067                 }
1068 );
1069
1070 1;