]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/SuperCat.pm
improving ISBN based unapi stuff
[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
501                 ->request(
502                         "open-ils.cstore.direct.$type.record_entry.id_list.atomic",
503                         { $axis => { ">" => $when }, id => { '>' => 0 } },
504                         { order_by => "$axis desc", limit => $limit } )
505                 ->gather(1);
506 }
507
508 for my $t ( qw/biblio authority/ ) {
509         for my $a ( qw/import edit/ ) {
510
511                 __PACKAGE__->register_method(
512                         method    => 'recent_changes',
513                         api_name  => "open-ils.supercat.$t.record.$a.recent",
514                         api_level => 1,
515                         argc      => 0,
516                         signature =>
517                                 { desc     => "Returns a list of recently ${a}ed $t records",
518                                   params   =>
519                                         [
520                                                 { name => 'when',
521                                                   desc => "Date to start looking for ${a}ed records",
522                                                   default => 'today',
523                                                   type => 'string' },
524
525                                                 { name => 'limit',
526                                                   desc => "Maximum count to retrieve",
527                                                   type => 'number' },
528                                         ],
529                                   'return' =>
530                                         { desc => "An id list of $t records",
531                                           type => 'array' }
532                                 },
533                 );
534         }
535 }
536
537
538 sub retrieve_record_marcxml {
539         my $self = shift;
540         my $client = shift;
541         my $rid = shift;
542
543         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
544
545         my $record = $_storage->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $rid )->gather(1);
546         return entityize( $record->marc ) if ($record);
547         return undef;
548 }
549
550 __PACKAGE__->register_method(
551         method    => 'retrieve_record_marcxml',
552         api_name  => 'open-ils.supercat.record.marcxml.retrieve',
553         api_level => 1,
554         argc      => 1,
555         signature =>
556                 { desc     => <<"                 DESC",
557 Returns the MARCXML representation of the requested bibliographic record
558                   DESC
559                   params   =>
560                         [
561                                 { name => 'bibId',
562                                   desc => 'An OpenILS biblio::record_entry id',
563                                   type => 'number' },
564                         ],
565                   'return' =>
566                         { desc => 'The bib record in MARCXML',
567                           type => 'string' }
568                 }
569 );
570
571 sub retrieve_isbn_marcxml {
572         my $self = shift;
573         my $client = shift;
574         my $isbn = shift;
575
576         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
577
578         my $recs = $_storage->request(
579                         'open-ils.cstore.direct.metabib.full_rec.search.atomic',
580                         { tag => { like => '02%'}, value => {like => "$isbn\%"}}
581         )->gather(1);
582
583         return undef unless (@$recs);
584
585         my $record = $_storage->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $recs->[0]->record )->gather(1);
586         return entityize( $record->marc ) if ($record);
587         return undef;
588 }
589
590 __PACKAGE__->register_method(
591         method    => 'retrieve_isbn_marcxml',
592         api_name  => 'open-ils.supercat.isbn.marcxml.retrieve',
593         api_level => 1,
594         argc      => 1,
595         signature =>
596                 { desc     => <<"                 DESC",
597 Returns the MARCXML representation of the requested ISBN
598                   DESC
599                   params   =>
600                         [
601                                 { name => 'ISBN',
602                                   desc => 'An ... um ... ISBN',
603                                   type => 'string' },
604                         ],
605                   'return' =>
606                         { desc => 'The bib record in MARCXML',
607                           type => 'string' }
608                 }
609 );
610
611 sub retrieve_record_transform {
612         my $self = shift;
613         my $client = shift;
614         my $rid = shift;
615
616         (my $transform = $self->api_name) =~ s/^.+record\.([^\.]+)\.retrieve$/$1/o;
617
618         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
619         $_storage->connect;
620
621         my $record = $_storage->request(
622                 'open-ils.cstore.direct.biblio.record_entry.retrieve',
623                 $rid
624         )->gather(1);
625
626         return undef unless ($record);
627
628         return entityize($record_xslt{$transform}{xslt}->transform( $_parser->parse_string( $record->marc ) )->toString);
629 }
630
631 sub retrieve_isbn_transform {
632         my $self = shift;
633         my $client = shift;
634         my $isbn = shift;
635
636         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
637
638         my $recs = $_storage->request(
639                         'open-ils.cstore.direct.metabib.full_rec.search.atomic',
640                         { tag => { like => '02%'}, value => {like => "$isbn\%"}}
641         )->gather(1);
642
643         return undef unless (@$recs);
644
645         (my $transform = $self->api_name) =~ s/^.+isbn\.([^\.]+)\.retrieve$/$1/o;
646
647         my $record = $_storage->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $recs->[0]->record )->gather(1);
648
649         return undef unless ($record);
650
651         return entityize($record_xslt{$transform}{xslt}->transform( $_parser->parse_string( $record->marc ) )->toString);
652 }
653
654 sub retrieve_record_objects {
655         my $self = shift;
656         my $client = shift;
657         my $ids = shift;
658
659         $ids = [$ids] unless (ref $ids);
660         $ids = [grep {$_} @$ids];
661
662         return [] unless (@$ids);
663
664         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
665         return $_storage->request('open-ils.cstore.direct.biblio.record_entry.search.atomic' => { id => [grep {$_} @$ids] })->gather(1);
666 }
667 __PACKAGE__->register_method(
668         method    => 'retrieve_record_objects',
669         api_name  => 'open-ils.supercat.record.object.retrieve',
670         api_level => 1,
671         argc      => 1,
672         signature =>
673                 { desc     => <<"                 DESC",
674 Returns the Fieldmapper object representation of the requested bibliographic records
675                   DESC
676                   params   =>
677                         [
678                                 { name => 'bibIds',
679                                   desc => 'OpenILS biblio::record_entry ids',
680                                   type => 'array' },
681                         ],
682                   'return' =>
683                         { desc => 'The bib records',
684                           type => 'array' }
685                 }
686 );
687
688
689 sub retrieve_isbn_object {
690         my $self = shift;
691         my $client = shift;
692         my $isbn = shift;
693
694         return undef unless ($isbn);
695
696         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
697         my $recs = $_storage->request(
698                         'open-ils.cstore.direct.metabib.full_rec.search.atomic',
699                         { tag => { like => '02%'}, value => {like => "$isbn\%"}}
700         )->gather(1);
701
702         return undef unless (@$recs);
703
704         return $_storage->request(
705                 'open-ils.cstore.direct.biblio.record_entry.search.atomic',
706                 { id => $recs->[0]->record }
707         )->gather(1);
708 }
709 __PACKAGE__->register_method(
710         method    => 'retrieve_isbn_object',
711         api_name  => 'open-ils.supercat.isbn.object.retrieve',
712         api_level => 1,
713         argc      => 1,
714         signature =>
715                 { desc     => <<"                 DESC",
716 Returns the Fieldmapper object representation of the requested bibliographic record
717                   DESC
718                   params   =>
719                         [
720                                 { name => 'isbn',
721                                   desc => 'an ISBN',
722                                   type => 'string' },
723                         ],
724                   'return' =>
725                         { desc => 'The bib record',
726                           type => 'object' }
727                 }
728 );
729
730
731
732 sub retrieve_metarecord_mods {
733         my $self = shift;
734         my $client = shift;
735         my $rid = shift;
736
737         my $_storage = OpenSRF::AppSession->connect( 'open-ils.cstore' );
738
739         # Get the metarecord in question
740         my $mr =
741         $_storage->request(
742                 'open-ils.cstore.direct.metabib.metarecord.retrieve' => $rid
743         )->gather(1);
744
745         # Now get the map of all bib records for the metarecord
746         my $recs =
747         $_storage->request(
748                 'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
749                 {metarecord => $rid}
750         )->gather(1);
751
752         $logger->debug("Adding ".scalar(@$recs)." bib record to the MODS of the metarecord");
753
754         # and retrieve the lead (master) record as MODS
755         my ($master) =
756                 $self   ->method_lookup('open-ils.supercat.record.mods.retrieve')
757                         ->run($mr->master_record);
758         my $master_mods = $_parser->parse_string($master)->documentElement;
759         $master_mods->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
760
761         # ... and a MODS clone to populate, with guts removed.
762         my $mods = $_parser->parse_string($master)->documentElement;
763         $mods->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
764         ($mods) = $mods->findnodes('//mods:mods');
765         $mods->removeChildNodes;
766
767         # Add the metarecord ID as a (locally defined) info URI
768         my $recordInfo = $mods
769                 ->ownerDocument
770                 ->createElement("mods:recordInfo");
771
772         my $recordIdentifier = $mods
773                 ->ownerDocument
774                 ->createElement("mods:recordIdentifier");
775
776         my ($year,$month,$day) = reverse( (localtime)[3,4,5] );
777         $year += 1900;
778         $month += 1;
779
780         my $id = $mr->id;
781         $recordIdentifier->appendTextNode(
782                 sprintf("tag:open-ils.org,$year-\%0.2d-\%0.2d:metabib-metarecord/$id", $month, $day)
783         );
784
785         $recordInfo->appendChild($recordIdentifier);
786         $mods->appendChild($recordInfo);
787
788         # Grab the title, author and ISBN for the master record and populate the metarecord
789         my ($title) = $master_mods->findnodes( './mods:titleInfo[not(@type)]' );
790         
791         if ($title) {
792                 $title->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
793                 $title = $mods->ownerDocument->importNode($title);
794                 $mods->appendChild($title);
795         }
796
797         my ($author) = $master_mods->findnodes( './mods:name[mods:role/mods:text[text()="creator"]]' );
798         if ($author) {
799                 $author->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
800                 $author = $mods->ownerDocument->importNode($author);
801                 $mods->appendChild($author);
802         }
803
804         my ($isbn) = $master_mods->findnodes( './mods:identifier[@type="isbn"]' );
805         if ($isbn) {
806                 $isbn->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
807                 $isbn = $mods->ownerDocument->importNode($isbn);
808                 $mods->appendChild($isbn);
809         }
810
811         # ... and loop over the constituent records
812         for my $map ( @$recs ) {
813
814                 # get the MODS
815                 my ($rec) =
816                         $self   ->method_lookup('open-ils.supercat.record.mods.retrieve')
817                                 ->run($map->source);
818
819                 my $part_mods = $_parser->parse_string($rec);
820                 $part_mods->documentElement->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
821                 ($part_mods) = $part_mods->findnodes('//mods:mods');
822
823                 for my $node ( ($part_mods->findnodes( './mods:subject' )) ) {
824                         $node->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
825                         $node = $mods->ownerDocument->importNode($node);
826                         $mods->appendChild( $node );
827                 }
828
829                 my $relatedItem = $mods
830                         ->ownerDocument
831                         ->createElement("mods:relatedItem");
832
833                 $relatedItem->setAttribute( type => 'constituent' );
834
835                 my $identifier = $mods
836                         ->ownerDocument
837                         ->createElement("mods:identifier");
838
839                 $identifier->setAttribute( type => 'uri' );
840
841                 my $subRecordInfo = $mods
842                         ->ownerDocument
843                         ->createElement("mods:recordInfo");
844
845                 my $subRecordIdentifier = $mods
846                         ->ownerDocument
847                         ->createElement("mods:recordIdentifier");
848
849                 my $subid = $map->source;
850                 $subRecordIdentifier->appendTextNode(
851                         sprintf("tag:open-ils.org,$year-\%0.2d-\%0.2d:biblio-record_entry/$subid",
852                                 $month,
853                                 $day
854                         )
855                 );
856                 $subRecordInfo->appendChild($subRecordIdentifier);
857
858                 $relatedItem->appendChild( $subRecordInfo );
859
860                 my ($tor) = $part_mods->findnodes( './mods:typeOfResource' );
861                 $tor->setNamespace( "http://www.loc.gov/mods/", "mods", 1 ) if ($tor);
862                 $tor = $mods->ownerDocument->importNode($tor) if ($tor);
863                 $relatedItem->appendChild($tor) if ($tor);
864
865                 if ( my ($part_isbn) = $part_mods->findnodes( './mods:identifier[@type="isbn"]' ) ) {
866                         $part_isbn->setNamespace( "http://www.loc.gov/mods/", "mods", 1 );
867                         $part_isbn = $mods->ownerDocument->importNode($part_isbn);
868                         $relatedItem->appendChild( $part_isbn );
869
870                         if (!$isbn) {
871                                 $isbn = $mods->appendChild( $part_isbn->cloneNode(1) );
872                         }
873                 }
874
875                 $mods->appendChild( $relatedItem );
876
877         }
878
879         $_storage->disconnect;
880
881         return entityize($mods->toString);
882
883 }
884 __PACKAGE__->register_method(
885         method    => 'retrieve_metarecord_mods',
886         api_name  => 'open-ils.supercat.metarecord.mods.retrieve',
887         api_level => 1,
888         argc      => 1,
889         signature =>
890                 { desc     => <<"                 DESC",
891 Returns the MODS representation of the requested metarecord
892                   DESC
893                   params   =>
894                         [
895                                 { name => 'metarecordId',
896                                   desc => 'An OpenILS metabib::metarecord id',
897                                   type => 'number' },
898                         ],
899                   'return' =>
900                         { desc => 'The metarecord in MODS',
901                           type => 'string' }
902                 }
903 );
904
905 sub list_metarecord_formats {
906         my @list = (
907                 { mods =>
908                         { namespace_uri   => 'http://www.loc.gov/mods/',
909                           docs            => 'http://www.loc.gov/mods/',
910                           schema_location => 'http://www.loc.gov/standards/mods/mods.xsd',
911                         }
912                 }
913         );
914
915         for my $type ( keys %metarecord_xslt ) {
916                 push @list,
917                         { $type => 
918                                 { namespace_uri   => $metarecord_xslt{$type}{namespace_uri},
919                                   docs            => $metarecord_xslt{$type}{docs},
920                                   schema_location => $metarecord_xslt{$type}{schema_location},
921                                 }
922                         };
923         }
924
925         return \@list;
926 }
927 __PACKAGE__->register_method(
928         method    => 'list_metarecord_formats',
929         api_name  => 'open-ils.supercat.metarecord.formats',
930         api_level => 1,
931         argc      => 0,
932         signature =>
933                 { desc     => <<"                 DESC",
934 Returns the list of valid metarecord formats that supercat understands.
935                   DESC
936                   'return' =>
937                         { desc => 'The format list',
938                           type => 'array' }
939                 }
940 );
941
942
943 sub list_record_formats {
944         my @list = (
945                 { marcxml =>
946                         { namespace_uri   => 'http://www.loc.gov/MARC21/slim',
947                           docs            => 'http://www.loc.gov/marcxml/',
948                           schema_location => 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd',
949                         }
950                 }
951         );
952
953         for my $type ( keys %record_xslt ) {
954                 push @list,
955                         { $type => 
956                                 { namespace_uri   => $record_xslt{$type}{namespace_uri},
957                                   docs            => $record_xslt{$type}{docs},
958                                   schema_location => $record_xslt{$type}{schema_location},
959                                 }
960                         };
961         }
962
963         return \@list;
964 }
965 __PACKAGE__->register_method(
966         method    => 'list_record_formats',
967         api_name  => 'open-ils.supercat.record.formats',
968         api_level => 1,
969         argc      => 0,
970         signature =>
971                 { desc     => <<"                 DESC",
972 Returns the list of valid record formats that supercat understands.
973                   DESC
974                   'return' =>
975                         { desc => 'The format list',
976                           type => 'array' }
977                 }
978 );
979 __PACKAGE__->register_method(
980         method    => 'list_record_formats',
981         api_name  => 'open-ils.supercat.isbn.formats',
982         api_level => 1,
983         argc      => 0,
984         signature =>
985                 { desc     => <<"                 DESC",
986 Returns the list of valid record formats that supercat understands.
987                   DESC
988                   'return' =>
989                         { desc => 'The format list',
990                           type => 'array' }
991                 }
992 );
993
994
995 sub oISBN {
996         my $self = shift;
997         my $client = shift;
998         my $isbn = shift;
999
1000         throw OpenSRF::EX::InvalidArg ('I need an ISBN please')
1001                 unless (length($isbn) >= 10);
1002
1003         my $_storage = OpenSRF::AppSession->create( 'open-ils.cstore' );
1004
1005         # Create a storage session, since we'll be making muliple requests.
1006         $_storage->connect;
1007
1008         # Find the record that has that ISBN.
1009         my $bibrec = $_storage->request(
1010                 'open-ils.cstore.direct.metabib.full_rec.search.atomic',
1011                 { tag => '020', subfield => 'a', value => { like => lc($isbn).'%'} }
1012         )->gather(1);
1013
1014         # Go away if we don't have one.
1015         return {} unless (@$bibrec);
1016
1017         # Find the metarecord for that bib record.
1018         my $mr = $_storage->request(
1019                 'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
1020                 {source => $bibrec->[0]->record}
1021         )->gather(1);
1022
1023         # Find the other records for that metarecord.
1024         my $records = $_storage->request(
1025                 'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
1026                 {metarecord => $mr->[0]->metarecord}
1027         )->gather(1);
1028
1029         # Just to be safe.  There's currently no unique constraint on sources...
1030         my %unique_recs = map { ($_->source, 1) } @$records;
1031         my @rec_list = sort keys %unique_recs;
1032
1033         # And now fetch the ISBNs for thos records.
1034         my $recs = [];
1035         push @$recs,
1036                 $_storage->request(
1037                         'open-ils.cstore.direct.metabib.full_rec.search',
1038                         { tag => '020', subfield => 'a', record => $_ }
1039                 )->gather(1) for (@rec_list);
1040
1041         # We're done with the storage server session.
1042         $_storage->disconnect;
1043
1044         # Return the oISBN data structure.  This will be XMLized at a higher layer.
1045         return
1046                 { metarecord => $mr->[0]->metarecord,
1047                   record_list => { map { ($_->record, $_->value) } @$recs } };
1048
1049 }
1050 __PACKAGE__->register_method(
1051         method    => 'oISBN',
1052         api_name  => 'open-ils.supercat.oisbn',
1053         api_level => 1,
1054         argc      => 1,
1055         signature =>
1056                 { desc     => <<"                 DESC",
1057 Returns the ISBN list for the metarecord of the requested isbn
1058                   DESC
1059                   params   =>
1060                         [
1061                                 { name => 'isbn',
1062                                   desc => 'An ISBN.  Duh.',
1063                                   type => 'string' },
1064                         ],
1065                   'return' =>
1066                         { desc => 'record to isbn map',
1067                           type => 'object' }
1068                 }
1069 );
1070
1071 1;