]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Cat.pm
fixed typo
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Cat.pm
1 use strict; use warnings;
2 package OpenILS::Application::Cat;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::Application;
5 use OpenILS::Application::Cat::Utils;
6 use OpenILS::Application::Cat::Merge;
7 use base qw/OpenSRF::Application/;
8 use Time::HiRes qw(time);
9 use OpenSRF::EX qw(:try);
10 use JSON;
11 use OpenILS::Utils::Fieldmapper;
12 use OpenILS::Event;
13
14 use XML::LibXML;
15 use Unicode::Normalize;
16 use Data::Dumper;
17 use OpenILS::Utils::FlatXML;
18 use OpenILS::Utils::Editor q/:funcs/;
19 use OpenILS::Perm;
20 use OpenSRF::Utils::SettingsClient;
21 use OpenSRF::Utils::Logger qw($logger);
22
23 my $apputils = "OpenILS::Application::AppUtils";
24
25 my $utils = "OpenILS::Application::Cat::Utils";
26 my $U = "OpenILS::Application::AppUtils";
27
28 my $conf;
29
30 my %marctemplates;
31
32 sub entityize { 
33         my $stuff = shift;
34         my $form = shift || "";
35
36         if ($form eq 'D') {
37                 $stuff = NFD($stuff);
38         } else {
39                 $stuff = NFC($stuff);
40         }
41
42         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
43         return $stuff;
44 }
45
46 __PACKAGE__->register_method(
47         method  => "retrieve_marc_template",
48         api_name        => "open-ils.cat.biblio.marc_template.retrieve",
49         notes           => <<"  NOTES");
50         Returns a MARC 'record tree' based on a set of pre-defined templates.
51         Templates include : book
52         NOTES
53
54 sub retrieve_marc_template {
55         my( $self, $client, $type ) = @_;
56
57         return $marctemplates{$type} if defined($marctemplates{$type});
58         $marctemplates{$type} = _load_marc_template($type);
59         return $marctemplates{$type};
60 }
61
62 sub _load_marc_template {
63         my $type = shift;
64
65         if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
66
67         my $template = $conf->config_value(                                     
68                 "apps", "open-ils.cat","app_settings", "marctemplates", $type );
69         warn "Opening template file $template\n";
70
71         open( F, $template ) or 
72                 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
73
74         my @xml = <F>;
75         close(F);
76         my $xml = join('', @xml);
77
78         return XML::LibXML->new->parse_string($xml)->documentElement->toString;
79 }
80
81
82
83 __PACKAGE__->register_method(
84         method  => "create_record_xml",
85         api_name        => "open-ils.cat.biblio.record.xml.create.override",
86         signature       => q/@see open-ils.cat.biblio.record.xml.create/);
87
88 __PACKAGE__->register_method(
89         method          => "create_record_xml",
90         api_name                => "open-ils.cat.biblio.record.xml.create",
91         signature       => q/
92                 Inserts a new biblio with the given XML
93         /
94 );
95
96 sub create_record_xml {
97         my( $self, $client, $login, $xml, $source ) = @_;
98         $source ||= 2;
99
100         my $override = 1 if $self->api_name =~ /override/;
101
102         my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
103         return $evt if $evt;
104
105         $logger->activity("user ".$user_obj->id." creating new MARC record");
106
107         my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
108
109         $meth = $self->method_lookup(
110                 "open-ils.cat.biblio.record.xml.import.override") if $override;
111
112         my ($s) = $meth->run($login, $xml, 2);
113         return $s;
114 }
115
116
117
118 __PACKAGE__->register_method(
119         method  => "biblio_record_replace_marc",
120         api_name        => "open-ils.cat.biblio.record.xml.update",
121         argc            => 3, 
122         signature       => q/
123                 Updates the XML for a given biblio record.
124                 This does not change any other aspect of the record entry
125                 exception the XML, the editor, and the edit date.
126                 @return The update record object
127         /
128 );
129
130 __PACKAGE__->register_method(
131         method          => 'biblio_record_replace_marc',
132         api_name                => 'open-ils.cat.biblio.record.marc.replace',
133         signature       => q/
134                 @param auth The authtoken
135                 @param recid The record whose MARC we're replacing
136                 @param newxml The new xml to use
137         /
138 );
139
140 __PACKAGE__->register_method(
141         method          => 'biblio_record_replace_marc',
142         api_name                => 'open-ils.cat.biblio.record.marc.replace.override',
143         signature       => q/@see open-ils.cat.biblio.record.marc.replace/
144 );
145
146 sub biblio_record_replace_marc  {
147         my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
148
149         my $e = new_editor(authtoken => $auth, xact => 1);
150         warn "EDITOR : xact = " . $e->{xact} . "\n";
151
152         return $e->event unless $e->checkauth;
153         return $e->event unless $e->allowed('CREATE_MARC');
154
155         my $fixtcn = $self->api_name =~ /replace/o;
156
157         # See if there is a different record in the database that has our TCN value
158         # If we're not updating the TCN, all we care about it the marcdoc
159         my $override = $self->api_name =~ /override/;
160         my( $tcn, $tsource, $marcdoc, $evt) = 
161                 _find_tcn_info($e->session, $newxml, $override, $recid);
162
163         return $evt if $evt;
164
165         my $rec = $e->retrieve_biblio_record_entry($recid)
166                 or return $e->event;
167
168         if( $fixtcn ) {
169                 # If we're here, it means we have new MARC and a new source for the MARC for this record
170                 $rec->tcn_value($tcn);
171                 $rec->tcn_source($tcn);
172         }
173
174         # XXX Make the source the ID from config.bib_source
175         $rec->source($source) if ($source);
176         $rec->editor($e->requestor->id);
177         $rec->edit_date('now');
178         $rec->marc( entityize( $marcdoc->documentElement->toString ) );
179
180         $logger->activity("user ".$e->requestor->id." replacing MARC for record $recid");
181
182         $e->update_biblio_record_entry($rec) or return $e->event;
183         $e->request('open-ils.worm.wormize.biblio', $recid) or return $e->event;
184         $e->commit;
185
186         return $rec;
187 }
188
189
190
191
192 __PACKAGE__->register_method(
193         method  => "biblio_record_xml_import",
194         api_name        => "open-ils.cat.biblio.record.xml.import.override",
195         signature       => q/@see open-ils.cat.biblio.record.xml.import/);
196
197 __PACKAGE__->register_method(
198         method  => "biblio_record_xml_import",
199         api_name        => "open-ils.cat.biblio.record.xml.import",
200         notes           => <<"  NOTES");
201         Takes a marcxml record and imports the record into the database.  In this
202         case, the marcxml record is assumed to be a complete record (i.e. valid
203         MARC).  The title control number is taken from (whichever comes first)
204         tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
205         in the database.
206         user_session must have IMPORT_MARC permissions
207         NOTES
208
209
210 sub biblio_record_xml_import {
211         my( $self, $client, $authtoken, $xml, $source) = @_;
212
213
214         # XXX Make the source the ID from config.bib_source
215
216         my $override = 1 if $self->api_name =~ /override/;
217
218         my( $tcn, $tcn_source, $marcdoc );
219         my( $requestor, $evt ) = $U->checksesperm($authtoken, 'IMPORT_MARC');
220         return $evt if $evt;
221
222         my $session = $apputils->start_db_session();
223
224         ( $tcn, $tcn_source, $marcdoc, $evt ) = _find_tcn_info($session, $xml, $override);
225         return $evt if $evt;
226
227         $logger->activity("user ".$requestor->id.
228                 " creating new biblio entry with tcn=$tcn and tcn_source $tcn_source");
229
230         my $record = Fieldmapper::biblio::record_entry->new;
231
232         $record->source($source) if ($source);
233         $record->tcn_source($tcn_source);
234         $record->tcn_value($tcn);
235         $record->creator($requestor->id);
236         $record->editor($requestor->id);
237         $record->create_date('now');
238         $record->edit_date('now');
239         $record->marc( entityize( $marcdoc->documentElement->toString ) );
240
241         my $id = $session->request(
242                 "open-ils.storage.direct.biblio.record_entry.create", $record )->gather(1);
243
244         return $U->DB_UPDATE_FAILED($record) unless $id;
245         $record->id( $id );
246
247         $logger->info("marc create/import created new record $id");
248
249         $apputils->commit_db_session($session);
250
251         $logger->debug("Sending record off to be wormized");
252
253         my $stat = $U->storagereq( 'open-ils.worm.wormize.biblio', $id );
254         throw OpenSRF::EX::ERROR 
255                 ("Unable to wormize imported record") unless $stat;
256
257         return $record;
258 }
259
260
261 sub _find_tcn_info { 
262         my $session             = shift;
263         my $xml                 = shift;
264         my $override    = shift;
265         my $existing_rec        = shift || 0;
266
267         # parse the XML
268         my $marcxml = XML::LibXML->new->parse_string( $xml );
269         $marcxml->documentElement->setNamespace( 
270                 "http://www.loc.gov/MARC21/slim", "marc", 1 );
271
272         my $xpath = '//marc:controlfield[@tag="001"]';
273         my $tcn = $marcxml->documentElement->findvalue($xpath);
274         $logger->info("biblio import located 001 (tcn) value of $tcn");
275
276         $xpath = '//marc:controlfield[@tag="003"]';
277         my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
278
279         if(my $rec = _tcn_exists($session, $tcn, $tcn_source, $existing_rec) ) {
280
281                 my $origtcn = $tcn;
282                 $tcn = find_free_tcn( $marcxml, $session, $existing_rec );
283
284                 # if we're overriding, try to find a different TCN to use
285                 if( $override ) {
286
287                         $logger->activity("tcn value $tcn already exists, attempting to override");
288
289                         if(!$tcn) {
290                                 return ( 
291                                         undef, 
292                                         undef, 
293                                         undef,
294                                         OpenILS::Event->new(
295                                                 'OPEN_TCN_NOT_FOUND', 
296                                                         payload => $marcxml->toString())
297                                         );
298                         }
299
300                 } else {
301
302                         $logger->warn("tcn value $origtcn already exists in import/create");
303
304                         # otherwise, return event
305                         return ( 
306                                 undef, 
307                                 undef, 
308                                 undef,
309                                 OpenILS::Event->new( 
310                                         'TCN_EXISTS', payload => { 
311                                                 dup_record      => $rec, 
312                                                 tcn                     => $origtcn,
313                                                 new_tcn         => $tcn
314                                                 }
315                                         )
316                                 );
317                 }
318         }
319
320         return ($tcn, $tcn_source, $marcxml);
321 }
322
323 sub find_free_tcn {
324
325         my $marcxml = shift;
326         my $session = shift;
327         my $existing_rec = shift;
328
329         my $add_039 = 0;
330
331         my $xpath = '//marc:datafield[@tag="039"]/subfield[@code="a"]';
332         my ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
333         $xpath = '//marc:datafield[@tag="039"]/subfield[@code="b"]';
334         my $tcn_source = $marcxml->documentElement->findvalue($xpath) || "System Local";
335
336         if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {
337                 $tcn = undef;
338         } else {
339                 $add_039++;
340         }
341
342
343         if(!$tcn) {
344                 $xpath = '//marc:datafield[@tag="020"]/subfield[@code="a"]';
345                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
346                 $tcn_source = "ISBN";
347                 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
348         }
349
350         if(!$tcn) { 
351                 $xpath = '//marc:datafield[@tag="022"]/subfield[@code="a"]';
352                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
353                 $tcn_source = "ISSN";
354                 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
355         }
356
357         if(!$tcn) {
358                 $xpath = '//marc:datafield[@tag="010"]';
359                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
360                 $tcn_source = "LCCN";
361                 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
362         }
363
364         if(!$tcn) {
365                 $xpath = '//marc:datafield[@tag="035"]/subfield[@code="a"]';
366                 ($tcn) = $marcxml->documentElement->findvalue($xpath) =~ /(\w+)\s*$/o;
367                 $tcn_source = "System Legacy";
368                 if(_tcn_exists($session, $tcn, $tcn_source, $existing_rec)) {$tcn = undef;}
369
370                 if($tcn) {
371                         $marcxml->documentElement->removeChild(
372                                 $marcxml->documentElement->findnodes( '//datafield[@tag="035"]' )
373                         );
374                 }
375         }
376
377         return undef unless $tcn;
378
379         if ($add_039) {
380                 my $df = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'datafield');
381                 $df->setAttribute( tag => '039' );
382                 $df->setAttribute( ind1 => ' ' );
383                 $df->setAttribute( ind2 => ' ' );
384                 $marcxml->documentElement->appendChild( $df );
385
386                 my $sfa = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
387                 $sfa->setAttribute( code => 'a' );
388                 $sfa->appendChild( $marcxml->createTextNode( $tcn ) );
389                 $df->appendChild( $sfa );
390
391                 my $sfb = $marcxml->createElementNS( 'http://www.loc.gov/MARC21/slim', 'subfield');
392                 $sfb->setAttribute( code => 'b' );
393                 $sfb->appendChild( $marcxml->createTextNode( $tcn_source ) );
394                 $df->appendChild( $sfb );
395         }
396
397         return $tcn;
398 }
399
400
401
402 sub _tcn_exists {
403         my $session = shift;
404         my $tcn = shift;
405         my $source = shift;
406         my $existing_rec ||= 0;
407
408         if(!$tcn) {return 0;}
409
410         $logger->debug("tcn_exists search for tcn $tcn and source $source");
411
412         # XXX why does the source matter?
413 #       my $req = $session->request(      
414 #               "open-ils.storage.id_list.biblio.record_entry.search_where.atomic",
415 #               { tcn_value => $tcn, tcn_source => $source, deleted => 'f' } );
416
417         my $req = $session->request(      
418                 "open-ils.storage.id_list.biblio.record_entry.search_where.atomic",
419                 { tcn_value => $tcn, deleted => 'f', id => {'!=' => $existing_rec} } );
420
421         my $recs = $req->gather(1);
422
423         if($recs and $recs->[0]) {
424                 $logger->debug("_tcn_exists is true for tcn : $tcn ($source)");
425                 return $recs->[0];
426         }
427
428         $logger->debug("_tcn_exists is false for tcn : $tcn ($source)");
429         return 0;
430 }
431
432
433
434
435 # XXX deprecated. Remove me.
436
437 =head deprecated
438
439 __PACKAGE__->register_method(
440         method  => "biblio_record_tree_retrieve",
441         api_name        => "open-ils.cat.biblio.record.tree.retrieve",
442 );
443
444 sub biblio_record_tree_retrieve {
445
446         my( $self, $client, $recordid ) = @_;
447
448         my $name = "open-ils.storage.direct.biblio.record_entry.retrieve";
449         my $session = OpenSRF::AppSession->create( "open-ils.storage" );
450         my $request = $session->request( $name, $recordid );
451         my $marcxml = $request->gather(1);
452
453         if(!$marcxml) {
454                 throw OpenSRF::EX::ERROR 
455                         ("No record in database with id $recordid");
456         }
457
458         $session->disconnect();
459         $session->kill_me();
460
461         warn "turning into nodeset\n";
462         my $nodes = OpenILS::Utils::FlatXML->new()->xml_to_nodeset( $marcxml->marc ); 
463         warn "turning nodeset into tree\n";
464         my $tree = $utils->nodeset2tree( $nodes->nodeset );
465
466         $tree->owner_doc( $marcxml->id() );
467
468         warn "returning tree\n";
469
470         return $tree;
471 }
472 =cut
473
474
475 =head deprecate 
476 __PACKAGE__->register_method(
477         method  => "biblio_record_xml_update",
478         api_name        => "open-ils.cat.biblio.record.xml.update",
479         argc            => 3, #(session_id, biblio_tree ) 
480         notes           => <<'  NOTES');
481         Updates the XML of a biblio record entry
482         @param authtoken The session token for the staff updating the record
483         @param docID The record entry ID to update
484         @param xml The new MARCXML record
485         NOTES
486
487 sub biblio_record_xml_update {
488
489         my( $self, $client, $user_session,  $id, $xml ) = @_;
490
491         my $user_obj = $apputils->check_user_session($user_session); 
492
493         if($apputils->check_user_perms(
494                         $user_obj->id, $user_obj->home_ou, "UPDATE_MARC")) {
495                 return OpenILS::Perm->new("UPDATE_MARC"); 
496         }
497
498         $logger->activity("user ".$user_obj->id." updating biblio record $id");
499
500
501         my $session = OpenILS::Application::AppUtils->start_db_session();
502
503         warn "Retrieving biblio record from storage for update\n";
504
505         my $req1 = $session->request(
506                         "open-ils.storage.direct.biblio.record_entry.batch.retrieve", $id );
507         my $biblio = $req1->gather(1);
508
509         warn "retrieved doc $id\n";
510
511         my $doc = XML::LibXML->new->parse_string($xml);
512         throw OpenSRF::EX::ERROR ("Invalid XML in record update: $xml") unless $doc;
513
514         $biblio->marc( entityize( $doc->documentElement->toString ) );
515         $biblio->editor( $user_obj->id );
516         $biblio->edit_date( 'now' );
517
518         warn "Sending updated doc $id to db with xml ".$biblio->marc. "\n";
519
520         my $req = $session->request( 
521                 "open-ils.storage.direct.biblio.record_entry.update", $biblio );
522
523         $req->wait_complete;
524         my $status = $req->recv();
525         if( !$status || $status->isa("Error") || ! $status->content) {
526                 OpenILS::Application::AppUtils->rollback_db_session($session);
527                 if($status->isa("Error")) { throw $status ($status); }
528                 throw OpenSRF::EX::ERROR ("Error updating biblio record");
529         }
530         $req->finish();
531
532         # Send the doc to the wormer for wormizing
533         warn "Starting worm session\n";
534
535         my $success = 0;
536         my $wresp;
537
538         my $wreq = $session->request( "open-ils.worm.wormize.biblio", $id );
539
540         my $w = 0;
541         try {
542                 $w = $wreq->gather(1);
543
544         } catch Error with {
545                 my $e = shift;
546                 warn "wormizing failed, rolling back\n";
547                 OpenILS::Application::AppUtils->rollback_db_session($session);
548
549                 if($e) { throw $e ($e); }
550                 throw OpenSRF::EX::ERROR ("Wormizing Failed for $id" );
551         };
552
553         warn "Committing db session...\n";
554         OpenILS::Application::AppUtils->commit_db_session( $session );
555
556 #       $client->respond_complete($tree);
557
558         warn "Done wormizing\n";
559
560         #use Data::Dumper;
561         #warn "Returning tree:\n";
562         #warn Dumper $tree;
563
564         return $biblio;
565
566 }
567
568 =cut
569
570
571
572 __PACKAGE__->register_method(
573         method  => "biblio_record_record_metadata",
574         api_name        => "open-ils.cat.biblio.record.metadata.retrieve",
575         argc            => 1, #(session_id, biblio_tree ) 
576         notes           => "Walks the tree and commits any changed nodes " .
577                                         "adds any new nodes, and deletes any deleted nodes",
578 );
579
580 sub biblio_record_record_metadata {
581         my( $self, $client, $authtoken, $ids ) = @_;
582
583         return [] unless $ids and @$ids;
584
585         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
586         return $editor->event unless $editor->checkauth;
587         return $editor->event unless $editor->allowed('VIEW_USER');
588
589         my @results;
590
591         for(@$ids) {
592                 return $editor->event unless 
593                         my $rec = $editor->retrieve_biblio_record_entry($_);
594                 $rec->creator($editor->retrieve_actor_user($rec->creator));
595                 $rec->editor($editor->retrieve_actor_user($rec->editor));
596                 $rec->clear_marc; # slim the record down
597                 push( @results, $rec );
598         }
599
600         return \@results;
601 }
602
603
604
605 __PACKAGE__->register_method(
606         method  => "biblio_record_marc_cn",
607         api_name        => "open-ils.cat.biblio.record.marc_cn.retrieve",
608         argc            => 1, #(bib id ) 
609 );
610
611 sub biblio_record_marc_cn {
612         my( $self, $client, $id ) = @_;
613
614         my $session = OpenSRF::AppSession->create("open-ils.storage");
615         my $marc = $session
616                 ->request("open-ils.storage.direct.biblio.record_entry.retrieve", $id )
617                 ->gather(1)
618                 ->marc;
619
620         my $doc = XML::LibXML->new->parse_string($marc);
621         $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
622         
623         my @res;
624         for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
625                 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
626                 for my $x (@node) {
627                         my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
628                         push @res, {$tag => $cn} if ($cn);
629                 }
630         }
631
632         return \@res
633 }
634
635 sub _get_id_by_userid {
636
637         my @users = @_;
638         my @ids;
639
640         my $session = OpenSRF::AppSession->create( "open-ils.storage" );
641         my $request = $session->request( 
642                 "open-ils.storage.direct.actor.user.search.usrname.atomic", @users );
643
644         $request->wait_complete;
645         my $response = $request->recv();
646         if(!$request->complete) { 
647                 throw OpenSRF::EX::ERROR ("no response from storage on user retrieve");
648         }
649
650         if(UNIVERSAL::isa( $response, "Error")){
651                 throw $response ($response);
652         }
653
654         for my $u (@{$response->content}) {
655                 next unless ref($u);
656                 push @ids, $u->id();
657         }
658
659         $request->finish;
660         $session->disconnect;
661         $session->kill_me();
662
663         return @ids;
664 }
665
666
667 # commits metadata objects to the db
668 sub _update_record_metadata {
669
670         my ($session, @docs ) = @_;
671
672         for my $doc (@docs) {
673
674                 my $user_obj = $doc->{user};
675                 my $docid = $doc->{docid};
676
677                 warn "Updating metata for doc $docid\n";
678
679                 my $request = $session->request( 
680                         "open-ils.storage.direct.biblio.record_entry.retrieve", $docid );
681                 my $record = $request->gather(1);
682
683                 warn "retrieved record\n";
684                 my ($id) = _get_id_by_userid($user_obj->usrname);
685
686                 warn "got $id from _get_id_by_userid\n";
687                 $record->editor($id);
688                 
689                 warn "Grabbed the record, updating and moving on\n";
690
691                 $request = $session->request( 
692                         "open-ils.storage.direct.biblio.record_entry.update", $record );
693                 $request->gather(1);
694         }
695
696         warn "committing metarecord update\n";
697
698         return 1;
699 }
700
701
702
703 __PACKAGE__->register_method(
704         method  => "orgs_for_title",
705         api_name        => "open-ils.cat.actor.org_unit.retrieve_by_title"
706 );
707
708 sub orgs_for_title {
709         my( $self, $client, $record_id ) = @_;
710
711         my $vols = $apputils->simple_scalar_request(
712                 "open-ils.storage",
713                 "open-ils.storage.direct.asset.call_number.search_where.atomic",
714                 { record => $record_id, deleted => 'f' });
715
716         my $orgs = { map {$_->owning_lib => 1 } @$vols };
717         return [ keys %$orgs ];
718 }
719
720
721 __PACKAGE__->register_method(
722         method  => "retrieve_copies",
723         api_name        => "open-ils.cat.asset.copy_tree.retrieve");
724
725 __PACKAGE__->register_method(
726         method  => "retrieve_copies",
727         api_name        => "open-ils.cat.asset.copy_tree.global.retrieve");
728
729 # user_session may be null/undef
730 sub retrieve_copies {
731
732         my( $self, $client, $user_session, $docid, @org_ids ) = @_;
733
734         if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
735
736         $docid = "$docid";
737
738         warn " $$ retrieving copy tree for orgs @org_ids and doc $docid at " . time() . "\n";
739
740         # grabbing copy trees should be available for everyone..
741         if(!@org_ids and $user_session) {
742                 my $user_obj = 
743                         OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
744                         @org_ids = ($user_obj->home_ou);
745         }
746
747         if( $self->api_name =~ /global/ ) {
748                 warn "performing global copy_tree search for $docid\n";
749                 return _build_volume_list( { record => $docid } );
750
751         } else {
752
753                 my @all_vols;
754                 for my $orgid (@org_ids) {
755                         my $vols = _build_volume_list( 
756                                         { record => $docid, owning_lib => $orgid } );
757                         warn "Volumes built for org $orgid\n";
758                         push( @all_vols, @$vols );
759                 }
760                 
761                 warn " $$ Finished copy_tree at " . time() . "\n";
762                 return \@all_vols;
763         }
764
765         return undef;
766 }
767
768
769 sub _build_volume_list {
770         my $search_hash = shift;
771
772         $search_hash->{deleted} = 'f';
773
774         my      $session = OpenSRF::AppSession->create( "open-ils.storage" );
775         
776
777         my $request = $session->request( 
778                         "open-ils.storage.direct.asset.call_number.search.atomic", $search_hash );
779                         #"open-ils.storage.direct.asset.call_number.search.atomic", $search_hash );
780
781         my $vols = $request->gather(1);
782         my @volumes;
783
784         for my $volume (@$vols) {
785
786                 warn "Grabbing copies for volume: " . $volume->id . "\n";
787                 my $creq = $session->request(
788                         "open-ils.storage.direct.asset.copy.search_where.atomic", 
789                         { call_number => $volume->id , deleted => 'f' });
790                         #"open-ils.storage.direct.asset.copy.search.call_number.atomic", $volume->id );
791
792                 my $copies = $creq->gather(1);
793
794                 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies  ];
795
796                 $volume->copies($copies);
797
798                 push( @volumes, $volume );
799         }
800
801
802         $session->disconnect();
803         return \@volumes;
804
805 }
806
807
808 __PACKAGE__->register_method(
809         method  => "fleshed_copy_update",
810         api_name        => "open-ils.cat.asset.copy.fleshed.batch.update",);
811
812 __PACKAGE__->register_method(
813         method  => "fleshed_copy_update",
814         api_name        => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
815
816 sub fleshed_copy_update {
817         my( $self, $conn, $auth, $copies ) = @_;
818         my( $reqr, $evt ) = $U->checkses($auth);
819         return $evt if $evt;
820         my $editor = OpenILS::Utils::Editor->new(requestor => $reqr, xact => 1);
821         my $override = $self->api_name =~ /override/;
822         $evt = update_fleshed_copies( $editor, $override, undef, $copies);
823         return $evt if $evt;
824         $editor->finish;
825         $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
826         return 1;
827 }
828
829
830 __PACKAGE__->register_method(
831         method => 'merge',
832         api_name        => 'open-ils.cat.biblio.records.merge',
833         signature       => q/
834                 Merges a group of records
835                 @param auth The login session key
836                 @param master The id of the record all other r
837                         ecords should be merged into
838                 @param records Array of records to be merged into the master record
839                 @return 1 on success, Event on error.
840         /
841 );
842
843 sub merge {
844         my( $self, $conn, $auth, $master, $records ) = @_;
845         my( $reqr, $evt ) = $U->checkses($auth);
846         return $evt if $evt;
847         my $editor = OpenILS::Utils::Editor->new( requestor => $reqr, xact => 1 );
848         my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
849         return $v if $v;
850         $editor->finish;
851         return 1;
852 }
853
854
855
856
857 # ---------------------------------------------------------------------------
858 # ---------------------------------------------------------------------------
859
860 # returns true if the given title (id) has no un-deleted
861 # copies attached
862 sub title_is_empty {
863         my( $editor, $rid ) = @_;
864
865         my $cnlist = $editor->search_asset_call_number(
866                 { record => $rid, deleted => 'f' }, { idlist => 1 } );
867         return 1 unless @$cnlist;
868
869         for my $cn (@$cnlist) {
870                 my $copylist = $editor->search_asset_copy(
871                         { call_number => $cn, deleted => 'f' }, { idlist => 1 });
872                 return 0 if @$copylist; # false if we find any copies
873         }
874
875         return 1;
876 }
877
878
879 __PACKAGE__->register_method(
880         method  => "fleshed_volume_update",
881         api_name        => "open-ils.cat.asset.volume.fleshed.batch.update",);
882
883 __PACKAGE__->register_method(
884         method  => "fleshed_volume_update",
885         api_name        => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
886
887 sub fleshed_volume_update {
888         my( $self, $conn, $auth, $volumes ) = @_;
889         my( $reqr, $evt ) = $U->checkses($auth);
890         return $evt if $evt;
891
892         my $override = ($self->api_name =~ /override/);
893         my $editor = OpenILS::Utils::Editor->new( requestor => $reqr, xact => 1 );
894
895         for my $vol (@$volumes) {
896                 $logger->info("vol-update: investigating volume ".$vol->id);
897
898                 $vol->editor($reqr->id);
899                 $vol->edit_date('now');
900
901                 my $copies = $vol->copies;
902                 $vol->clear_copies;
903
904                 if( $vol->isdeleted ) {
905
906                         $logger->info("vol-update: deleting volume");
907                         my $cs = $editor->search_asset_copy(
908                                 { call_number => $vol->id, deleted => 'f' } );
909                         return OpenILS::Event->new(
910                                 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
911
912                         $vol->deleted('t');
913                         return $editor->event unless
914                                 $editor->update_asset_call_number($vol);
915
916                         
917                 } elsif( $vol->isnew ) {
918                         $logger->info("vol-update: creating volume");
919                         $evt = create_volume( $override, $editor, $vol );
920                         return $evt if $evt;
921
922                 } elsif( $vol->ischanged ) {
923                         $logger->info("vol-update: update volume");
924                         return $editor->event unless
925                                 $editor->update_asset_call_number($vol);
926                         return $evt if $evt;
927                 }
928
929                 # now update any attached copies
930                 if( @$copies and !$vol->isdeleted ) {
931                         $_->call_number($vol->id) for @$copies;
932                         $evt = update_fleshed_copies( $editor, $override, $vol, $copies );
933                         return $evt if $evt;
934                 }
935         }
936
937         $editor->finish;
938         return scalar(@$volumes);
939 }
940
941
942 # this does the actual work
943 sub update_fleshed_copies {
944         my( $editor, $override, $vol, $copies ) = @_;
945
946         my $evt;
947         my $fetchvol = ($vol) ? 0 : 1;
948
949         my %cache;
950         $cache{$vol->id} = $vol if $vol;
951
952         for my $copy (@$copies) {
953
954                 my $copyid = $copy->id;
955                 $logger->info("vol-update: inspecting copy $copyid");
956
957                 if( !($vol = $cache{$copy->call_number}) ) {
958                         $vol = $cache{$copy->call_number} = 
959                                 $editor->retrieve_asset_call_number($copy->call_number);
960                         return $editor->event unless $vol;
961                 }
962
963                 $copy->editor($editor->requestor->id);
964                 $copy->edit_date('now');
965
966                 $copy->status( $copy->status->id ) if ref($copy->status);
967                 $copy->location( $copy->location->id ) if ref($copy->location);
968                 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
969                 
970                 my $sc_entries = $copy->stat_cat_entries;
971                 $copy->clear_stat_cat_entries;
972
973                 if( $copy->isdeleted ) {
974                         $evt = delete_copy($editor, $override, $vol, $copy);
975                         return $evt if $evt;
976
977                 } elsif( $copy->isnew ) {
978                         $evt = create_copy( $editor, $vol, $copy );
979                         return $evt if $evt;
980
981                 } elsif( $copy->ischanged ) {
982
983                         $logger->info("vol-update: updating copy $copyid");
984                         return $editor->event unless
985                                 $editor->update_asset_copy(
986                                         $copy, {checkperm=>1, permorg=>$vol->owning_lib});
987                         return $evt if $evt;
988                 }
989
990                 $copy->stat_cat_entries( $sc_entries );
991                 $evt = update_copy_stat_entries($editor, $copy);
992                 return $evt if $evt;
993         }
994
995         $logger->debug("vol-update: done updating copy batch");
996
997         return undef;
998 }
999
1000 sub delete_copy {
1001         my( $editor, $override, $vol, $copy ) = @_;
1002
1003         $logger->info("vol-update: deleting copy ".$copy->id);
1004         $copy->deleted('t');
1005
1006         $editor->update_asset_copy(
1007                 $copy, {checkperm=>1, permorg=>$vol->owning_lib})
1008                 or return $editor->event;
1009
1010         if( title_is_empty($editor, $vol->record) ) {
1011
1012                 if( $override ) {
1013
1014                         # delete this volume if it's not already marked as deleted
1015                         if(!$vol->deleted || $vol->deleted =~ /f/io || ! $vol->isdeleted) {
1016                                 $vol->deleted('t');
1017                                 $editor->update_asset_call_number($vol, {checkperm=>0})
1018                                         or return $editor->event;
1019                         }
1020
1021                         # then delete the record this volume points to
1022                         my $rec = $editor->retrieve_biblio_record_entry($vol->record)
1023                                 or return $editor->event;
1024
1025                         if( !$rec->deleted ) {
1026                                 $rec->deleted('t');
1027                                 $rec->active('f');
1028                                 $editor->update_biblio_record_entry($rec, {checkperm=>0})
1029                                         or return $editor->event;
1030                         }
1031
1032                 } else {
1033                         return OpenILS::Event->new('TITLE_LAST_COPY');
1034                 }
1035         }
1036
1037         return undef;
1038 }
1039
1040 sub create_copy {
1041         my( $editor, $vol, $copy ) = @_;
1042
1043         my $existing = $editor->search_asset_copy(
1044                 { barcode => $copy->barcode } );
1045         
1046         return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1047
1048         $copy->clear_id;
1049         $copy->creator($editor->requestor->id);
1050         $copy->create_date('now');
1051
1052         $editor->create_asset_copy(
1053                 $copy, {checkperm=>1, permorg=>$vol->owning_lib})
1054                 or return $editor->event;
1055
1056         return undef;
1057 }
1058
1059 sub update_copy_stat_entries {
1060         my( $editor, $copy ) = @_;
1061
1062         my $evt;
1063         my $entries = $copy->stat_cat_entries;
1064         return undef unless ($entries and @$entries);
1065
1066         my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
1067
1068         if(!$copy->isnew) {
1069                 # if there is no stat cat entry on the copy who's id matches the
1070                 # current map's id, remove the map from the database
1071                 for my $map (@$maps) {
1072                         if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1073
1074                                 $logger->info("copy update found stale ".
1075                                         "stat cat entry map ".$map->id. " on copy ".$copy->id);
1076
1077                                 $editor->delete_asset_stat_cat_entry_copy_map($map)
1078                                         or return $editor->event;
1079                         }
1080                 }
1081         }
1082         
1083         # go through the stat cat update/create process
1084         for my $entry (@$entries) { 
1085
1086                 # if this link already exists in the DB, don't attempt to re-create it
1087                 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1088         
1089                 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1090                 
1091                 $new_map->stat_cat( $entry->stat_cat );
1092                 $new_map->stat_cat_entry( $entry->id );
1093                 $new_map->owning_copy( $copy->id );
1094
1095                 $editor->create_asset_stat_cat_entry_copy_map($new_map)
1096                         or return $editor->event;
1097
1098                 $logger->info("copy update created new stat cat entry map ".$editor->data);
1099         }
1100
1101         return undef;
1102 }
1103
1104
1105 sub create_volume {
1106         my( $override, $editor, $vol ) = @_;
1107         my $evt;
1108
1109
1110         # first lets see if there are any collisions
1111         my $vols = $editor->search_asset_call_number( { 
1112                         owning_lib      => $vol->owning_lib,
1113                         record          => $vol->record,
1114                         label                   => $vol->label,
1115                         deleted         => 'f'
1116                 }
1117         );
1118
1119         my $label = undef;
1120         if(@$vols) {
1121                 if($override) { 
1122                         $label = $vol->label;
1123                 } else {
1124                         return OpenILS::Event->new(
1125                                 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1126                 }
1127         }
1128
1129         # create a temp label so we can create the volume, then de-dup it
1130         $vol->label( '__SYSTEM_TMP_'.time) if $label;
1131
1132         $vol->creator($editor->requestor->id);
1133         $vol->create_date('now');
1134         $vol->clear_id;
1135
1136         $editor->create_asset_call_number($vol) or return $editor->event;
1137
1138         if($label) {
1139                 # now restore the label and merge into the existing record
1140                 $vol->label($label);
1141                 (undef, $evt) = 
1142                         OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1143                 return $evt if $evt;
1144         }
1145
1146         return undef;
1147 }
1148
1149
1150
1151
1152
1153
1154 1;