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