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