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