]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Cat.pm
added event for duplicate barcodes in copy create
[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 # -----------------------------------------------------------------
739 # Fleshed volume tree batch add/update.  This does everything a 
740 # volume tree could want, add, update, delete
741 # -----------------------------------------------------------------
742 __PACKAGE__->register_method(
743         method  => "volume_tree_fleshed_update",
744         api_name        => "open-ils.cat.asset.volume_tree.fleshed.batch.update",
745 );
746 sub volume_tree_fleshed_update {
747
748         my( $self, $client, $user_session, $volumes ) = @_;
749         return undef unless $volumes;
750
751         my $user_obj = $apputils->check_user_session($user_session);
752
753         # first lets see if we have any dup volume labels
754 #       my %volumes;
755 #       my @volumes = @$volumes;
756 #       for my $vol (@volumes) {
757 #               $volumes{$_->owning_lib} = {}  unless $volumes{$_->owning_lib};
758 #               $volumes{$_->record} = {}  unless $volumes{$_->record};
759 #               if($volumes{$_->record}->{$_->label}) {
760 #                       $logger->info("Duplicate volume label found ".
761 #                               "for record ".$_->record." and label ".$_->label);
762 #                       $volumes{$_->record}->{$_->label}++;
763 #               } else {
764 #                       $volumes{$_->record}->{$_->label} = 1;
765 #               }
766 #       }
767 #
768 #       for my $r (values %volumes) {
769 #               for my $l (keys %{$volumes{$r}}) {
770 #                       return OpenILS::Event->new('CALL_NUMBER_EXISTS', payload => $l)
771 #                               if $volumes{$r}{$l} > 1;
772 #               }
773 #       }
774
775
776         my $session = $apputils->start_db_session();
777         warn "Looping on volumes in fleshed volume tree update\n";
778
779         # cycle through the volumes provided and update/create/delete where necessary
780         for my $volume (@$volumes) {
781
782                 warn "updating volume " . $volume->id . "\n";
783
784                 my $update_copy_list = $volume->copies;
785
786
787                 if( $volume->isdeleted) {
788                         my $status = _delete_volume($session, $volume, $user_obj);
789                         #if(!$status) {
790                                 #throw OpenSRF::EX::ERROR
791                                         #("Volume delete failed for volume " . $volume->id);
792                         #}
793                         if(UNIVERSAL::isa($status, "Fieldmapper::perm_ex")) { return $status; }
794
795                 } elsif( $volume->isnew ) {
796
797                         $volume->clear_id;
798                         $volume->editor($user_obj->id);
799                         $volume->creator($user_obj->id);
800                         $volume = _add_volume($session, $volume, $user_obj);
801                         use Data::Dumper;
802                         warn Dumper $volume;
803                         if($volume and UNIVERSAL::isa($volume, "Fieldmapper::perm_ex")) { return $volume; }
804
805                 } elsif( $volume->ischanged ) {
806
807                         $volume->editor($user_obj->id);
808                         my $stat = _update_volume($session, $volume, $user_obj);
809                         if($stat and UNIVERSAL::isa($stat, "Fieldmapper::perm_ex")) { return $stat; }
810                 }
811
812
813                 if( ! $volume->isdeleted ) {
814                         for my $copy (@{$update_copy_list}) {
815         
816                                 $copy->editor($user_obj->id);
817                                 warn "updating copy for volume " . $volume->id . "\n";
818         
819                                 if( $copy->isnew ) {
820         
821                                         $copy->clear_id;
822                                         $copy->call_number($volume->id);
823                                         $copy->creator($user_obj->id);
824                                         $copy = _fleshed_copy_update($session,$copy,$user_obj);
825         
826                                 } elsif( $copy->ischanged ) {
827                                         $copy->call_number($volume->id);
828                                         $copy = _fleshed_copy_update($session, $copy, $user_obj);
829         
830                                 } elsif( $copy->isdeleted ) {
831                                         warn "Deleting copy " . $copy->id . " for volume " . $volume->id . "\n";
832                                         my $status = _fleshed_copy_update($session, $copy, $user_obj);
833                                         warn "Copy delete returned a status of $status\n";
834                                 }
835                         }
836                 }
837         }
838
839         $apputils->commit_db_session($session);
840         return scalar(@$volumes);
841 }
842
843
844 sub _delete_volume {
845         my( $session, $volume, $user_obj ) = @_;
846
847         if($apputils->check_user_perms(
848                         $user_obj->id, $user_obj->home_ou, "DELETE_VOLUME")) {
849                 return OpenILS::Perm->new("DELETE_VOLUME"); }
850
851         #$volume = _find_volume($session, $volume);
852         warn "Deleting volume " . $volume->id . "\n";
853
854         my $copies = $session->request(
855                 "open-ils.storage.direct.asset.copy.search_where.atomic", 
856                 { call_number => $volume->id, deleted => 'f' } )->gather(1);
857                 #"open-ils.storage.direct.asset.copy.search.call_number.atomic",
858
859         if(@$copies) {
860                 throw OpenSRF::EX::ERROR 
861                         ("Cannot remove volume with copies attached");
862         }
863
864         my $req = $session->request(
865                 "open-ils.storage.direct.asset.call_number.delete",
866                 $volume );
867         return $req->gather(1);
868 }
869
870
871 sub _update_volume {
872         my($session, $volume, $user_obj) = @_;
873         if($apputils->check_user_perms(
874                         $user_obj->id, $user_obj->home_ou, "UPDATE_VOLUME")) {
875                 return OpenILS::Perm->new("UPDATE_VOLUME"); }
876
877         my $req = $session->request(
878                 "open-ils.storage.direct.asset.call_number.update",
879                 $volume );
880         my $status = $req->gather(1);
881 }
882
883 sub _add_volume {
884
885         my($session, $volume, $user_obj) = @_;
886
887         if($apputils->check_user_perms(
888                         $user_obj->id, $user_obj->home_ou, "CREATE_VOLUME")) {
889                 warn "User does not have priveleges to create new volumes\n";
890                 return OpenILS::Perm->new("CREATE_VOLUME"); 
891         }
892
893         my $request = $session->request( 
894                 "open-ils.storage.direct.asset.call_number.create", $volume );
895
896         my $id = $request->gather(1);
897
898         if( $id == 0 ) {
899                 OpenILS::Application::AppUtils->rollback_db_session($session);
900                 throw OpenSRF::EX::ERROR (" * -> Error creating new volume");
901         }
902
903         $volume->id($id);
904         warn "received new volume id: $id\n";
905         return $volume;
906
907 }
908
909
910
911
912 __PACKAGE__->register_method(
913         method  => "fleshed_copy_update",
914         api_name        => "open-ils.cat.asset.copy.fleshed.batch.update",
915 );
916
917 sub fleshed_copy_update {
918         my($self, $client, $user_session, $copies) = @_;
919
920         my $user_obj = $apputils->check_user_session($user_session); 
921         my $session = $apputils->start_db_session();
922
923         for my $copy (@$copies) {
924                 _fleshed_copy_update($session, $copy, $user_obj);
925         }
926
927         $apputils->commit_db_session($session);
928         return 1;
929 }
930
931
932
933 sub _delete_copy {
934         my($session, $copy, $user_obj) = @_;
935
936         if($apputils->check_user_perms(
937                         $user_obj->id, $user_obj->home_ou, "DELETE_COPY")) {
938                 return OpenILS::Perm->new("DELETE_COPY"); }
939
940         warn "Deleting copy " . $copy->id . "\n";
941         my $request = $session->request(
942                 "open-ils.storage.direct.asset.copy.delete",
943                 $copy );
944         return $request->gather(1);
945 }
946
947 sub _create_copy {
948         my($session, $copy, $user_obj) = @_;
949
950         if($apputils->check_user_perms(
951                         $user_obj->id, $user_obj->home_ou, "CREATE_COPY")) {
952                 return OpenILS::Perm->new("CREATE_COPY"); }
953
954         my $request = $session->request(
955                 "open-ils.storage.direct.asset.copy.create",
956                 $copy );
957         my $id = $request->gather(1);
958
959         if($id < 1) {
960                 throw OpenSRF::EX::ERROR
961                         ("Unable to create new copy " . Dumper($copy));
962         }
963         $copy->id($id);
964         warn "Created copy " . $copy->id . "\n";
965
966         return $copy;
967
968 }
969
970 sub _update_copy {
971         my($session, $copy, $user_obj) = @_;
972
973         my $evt = $apputils->check_perms($user_obj->id, $copy->circ_lib, 'UPDATE_COPY');
974         return $evt if $evt; #XXX NOT YET HANDLED BY CALLER
975
976         my $status = $apputils->simplereq(      
977                 'open-ils.storage',
978                 "open-ils.storage.direct.asset.copy.update", $copy );
979         $logger->debug("Successfully updated copy " . $copy->id );
980         return $status;
981 }
982
983
984 # -----------------------------------------------------------------
985 # Creates/Updates/Deletes a fleshed asset.copy.  
986 # adds/deletes copy stat_cat maps where necessary
987 # -----------------------------------------------------------------
988 sub _fleshed_copy_update {
989         my($session, $copy, $editor) = @_;
990
991         my $stat_cat_entries = $copy->stat_cat_entries;
992         $copy->editor($editor->id);
993         
994         # in case we're fleshed
995         if(ref($copy->status))          {$copy->status( $copy->status->id ); }
996         if(ref($copy->location))        {$copy->location( $copy->location->id ); }
997         if(ref($copy->circ_lib))        {$copy->circ_lib( $copy->circ_lib->id ); }
998
999         warn "Updating copy " . Dumper($copy) . "\n";
1000
1001         if( $copy->isdeleted ) { 
1002                 return _delete_copy($session, $copy, $editor);
1003         } elsif( $copy->isnew ) {
1004                 $copy = _create_copy($session, $copy, $editor);
1005         } elsif( $copy->ischanged ) {
1006                 _update_copy($session, $copy, $editor);
1007         }
1008
1009         
1010         return 1 unless ( $stat_cat_entries and @$stat_cat_entries );
1011
1012         my $stat_maps = $session->request(
1013                 "open-ils.storage.direct.asset.stat_cat_entry_copy_map.search.owning_copy.atomic",
1014                 $copy->id )->gather(1);
1015
1016         if(!$copy->isnew) { _delete_stale_maps($session, $stat_maps, $copy); }
1017         
1018         # go through the stat cat update/create process
1019         for my $stat_entry (@{$stat_cat_entries}){ 
1020                 _copy_update_stat_cats( $session, $copy, $stat_maps, $stat_entry, $editor );
1021         }
1022         
1023         return 1;
1024 }
1025
1026
1027 # -----------------------------------------------------------------
1028 # Deletes stat maps attached to this copy in the database that
1029 # are no longer attached to the current copy
1030 # -----------------------------------------------------------------
1031 sub _delete_stale_maps {
1032         my( $session, $stat_maps, $copy) = @_;
1033
1034         warn "Deleting stale stat maps for copy " . $copy->id . "\n";
1035         for my $map (@$stat_maps) {
1036         # if there is no stat cat entry on the copy who's id matches the
1037         # current map's id, remove the map from the database
1038         if(! grep { $_->id == $map->stat_cat_entry } @{$copy->stat_cat_entries} ) {
1039                 my $req = $session->request(
1040                         "open-ils.storage.direct.asset.stat_cat_entry_copy_map.delete", $map );
1041                 $req->gather(1);
1042                 }
1043         }
1044
1045         return $stat_maps;
1046 }
1047
1048
1049 # -----------------------------------------------------------------
1050 # Searches the stat maps to see if '$entry' already exists on
1051 # the given copy.  If it does not, a new stat map is created
1052 # for the given entry and copy
1053 # -----------------------------------------------------------------
1054 sub _copy_update_stat_cats {
1055         my ( $session, $copy, $stat_maps, $entry, $editor ) = @_;
1056
1057         warn "Updating stat maps for copy " . $copy->id . "\n";
1058
1059         # see if this map already exists
1060         for my $map (@$stat_maps) {
1061                 if( $map->stat_cat_entry == $entry->id ) {return;}
1062         }
1063
1064         warn "Creating new stat map for stat  " . 
1065                 $entry->stat_cat . " and copy " . $copy->id . "\n";
1066
1067         # if not, create it
1068         my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1069
1070         $new_map->stat_cat( $entry->stat_cat );
1071         $new_map->stat_cat_entry( $entry->id );
1072         $new_map->owning_copy( $copy->id );
1073
1074         warn "New map is " . Dumper($new_map) . "\n";
1075
1076         my $request = $session->request(
1077                 "open-ils.storage.direct.asset.stat_cat_entry_copy_map.create",
1078                 $new_map );
1079         my $status = $request->gather(1);
1080         warn "created new map with id $status\n";
1081
1082 }
1083
1084
1085 __PACKAGE__->register_method(
1086         method => 'merge',
1087         api_name        => 'open-ils.cat.biblio.records.merge',
1088         signature       => q/
1089                 Merges a group of records
1090                 @param auth The login session key
1091                 @param master The id of the record all other r
1092                         ecords should be merged into
1093                 @param records Array of records to be merged into the master record
1094                 @return 1 on success, Event on error.
1095         /
1096 );
1097
1098 sub merge {
1099         my( $self, $conn, $auth, $master, $records ) = @_;
1100         my( $reqr, $evt ) = $U->checkses($auth);
1101         return $evt if $evt;
1102         my %r = map { $_->id => 1 } (@$records, $master); # unique the ids
1103         $records = [ keys %r ];
1104         my $editor = OpenILS::Utils::Editor->new( requestor => $reqr, xact => 1 );
1105         my $v = OpenILS::Application::Cat::Merge::merge_records($editor, $master, $records);
1106         return $v if $v;
1107         $editor->finish;
1108         return 1;
1109 }
1110
1111
1112
1113
1114 # ---------------------------------------------------------------------------
1115 # ---------------------------------------------------------------------------
1116
1117
1118 __PACKAGE__->register_method(
1119         method  => "fleshed_volume_update",
1120         api_name        => "open-ils.cat.asset.volume.fleshed.batch.update",
1121 );
1122 sub fleshed_volume_update {
1123         my( $self, $conn, $auth, $volumes ) = @_;
1124         my( $reqr, $evt ) = $U->checkses($auth);
1125         return $evt if $evt;
1126
1127         my $override = ($self->api_name =~ /override/);
1128         my $editor = OpenILS::Utils::Editor->new( requestor => $reqr, xact => 1 );
1129
1130         for my $vol (@$volumes) {
1131                 $logger->info("vol-update: investigating volume ".$vol->id);
1132
1133                 $vol->editor($reqr->id);
1134                 $vol->edit_date('now');
1135
1136                 my $copies = $vol->copies;
1137                 $vol->clear_copies;
1138
1139                 if( $vol->isdeleted ) {
1140
1141                         $logger->info("vol-update: deleting volume");
1142                         my $cs = $editor->search_asset_copy(
1143                                 { call_number => $vol->id, deleted => 'f' } );
1144                         return OpenILS::Event->new(
1145                                 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
1146
1147                         $vol->delete('t');
1148                         $evt = $editor->update_asset_call_number($vol);
1149                         return $evt if $evt;
1150                         
1151                 } elsif( $vol->isnew ) {
1152                         $logger->info("vol-update: creating volume");
1153                         $evt = create_volume( $override, $editor, $vol );
1154                         return $evt if $evt;
1155
1156                 } elsif( $vol->ischanged ) {
1157                         $logger->info("vol-update: update volume");
1158                         $evt = $editor->update_asset_call_number($vol);
1159                         return $evt if $evt;
1160                 }
1161
1162                 # now update any attached copies
1163                 if( @$copies and !$vol->isdeleted ) {
1164                         $_->call_number($vol->id) for @$copies;
1165                         $evt = update_fleshed_copies( $editor, $vol, $copies );
1166                         return $evt if $evt;
1167                 }
1168         }
1169
1170         $editor->finish;
1171         return scalar(@$volumes);
1172 }
1173
1174
1175 # this does the actual work
1176 sub update_fleshed_copies {
1177         my( $editor, $vol, $copies ) = @_;
1178
1179         my $evt;
1180         for my $copy (@$copies) {
1181
1182                 my $copyid = $copy->id;
1183                 $logger->info("vol-update: inspecting copy $copyid");
1184         
1185                 $copy->editor($editor->requestor->id);
1186                 $copy->edit_date('now');
1187                 $copy->call_number($vol->id);
1188
1189                 $copy->status( $copy->status->id ) if ref($copy->status);
1190                 $copy->location( $copy->location->id ) if ref($copy->location);
1191                 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1192                 
1193                 my $sc_entries = $copy->stat_cat_entries;
1194                 $copy->clear_stat_cat_entries;
1195
1196                 if( $copy->isdeleted ) {
1197
1198                         $logger->info("vol-update: deleting copy $copyid");
1199                         $copy->delete('t');
1200                         $evt = $editor->update_asset_copy(
1201                                 $copy, {checkperm=>1, org=>$vol->owning_lib});
1202                         return $evt if $evt;
1203
1204                 } elsif( $copy->isnew ) {
1205                         $evt = create_copy( $editor, $vol, $copy );
1206                         return $evt if $evt;
1207
1208                 } elsif( $copy->ischanged ) {
1209
1210                         $logger->info("vol-update: updating copy $copyid");
1211                         $evt = $editor->update_asset_copy(
1212                                 $copy, {checkperm=>1, org=>$vol->owning_lib});
1213                         return $evt if $evt;
1214                 }
1215
1216                 $copy->stat_cat_entries( $sc_entries );
1217                 $evt = update_copy_stat_entries($editor, $copy);
1218                 return $evt if $evt;
1219         }
1220
1221         return undef;
1222 }
1223
1224 sub create_copy {
1225         my( $editor, $vol, $copy ) = @_;
1226
1227         my $existing = $editor->search_asset_copy(
1228                 { call_number => $copy->call_number } );
1229         
1230         return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
1231
1232         $copy->clear_id;
1233         $copy->creator($editor->requestor->id);
1234         $copy->create_date('now');
1235
1236         my $evt = $editor->create_asset_copy(
1237                 $copy, {checkperm=>1, org=>$vol->owning_lib});
1238         return $evt if $evt;
1239
1240         $copy->id($editor->lastid);
1241         return undef;
1242 }
1243
1244 sub update_copy_stat_entries {
1245         my( $editor, $copy ) = @_;
1246
1247         my $evt;
1248         my $entries = $copy->stat_cat_entries;
1249         return undef unless ($entries and @$entries);
1250
1251         my $maps = $editor->search_asset_stat_cat_entry_copy_map({copy=>$copy->id});
1252
1253         if(!$copy->isnew) {
1254                 # if there is no stat cat entry on the copy who's id matches the
1255                 # current map's id, remove the map from the database
1256                 for my $map (@$maps) {
1257                         if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
1258
1259                                 $logger->info("copy update found stale ".
1260                                         "stat cat entry map ".$map->id. " on copy ".$copy->id);
1261
1262                                 $evt = $editor->delete_asset_stat_cat_entry_copy_map($map);
1263                                 return $evt if $evt;
1264                         }
1265                 }
1266         }
1267         
1268         # go through the stat cat update/create process
1269         for my $entry (@$entries) { 
1270
1271                 # if this link already exists in the DB, don't attempt to re-create it
1272                 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
1273         
1274                 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1275                 
1276                 $new_map->stat_cat( $entry->stat_cat );
1277                 $new_map->stat_cat_entry( $entry->id );
1278                 $new_map->owning_copy( $copy->id );
1279
1280                 $evt = $editor->create_asset_stat_cat_entry_copy_map($new_map);
1281                 return $evt if $evt;
1282
1283                 $logger->info("copy update created new stat cat entry map ".$editor->lastid);
1284         }
1285
1286         return undef;
1287 }
1288
1289
1290 sub create_volume {
1291         my( $override, $editor, $vol ) = @_;
1292         my $evt;
1293
1294
1295         # first lets see if there are any collisions
1296         my $vols = $editor->search_asset_call_number( { 
1297                         owning_lib      => $vol->owning_lib,
1298                         record          => $vol->record,
1299                         label                   => $vol->label
1300                 }
1301         );
1302
1303         my $label = undef;
1304         if(@$vols) {
1305                 if($override) { 
1306                         $label = $vol->label;
1307                 } else {
1308                         return OpenILS::Event->new(
1309                                 'VOLUME_LABEL_EXISTS', payload => $vol->id);
1310                 }
1311         }
1312
1313         # create a temp label so we can create the volume, then de-dup it
1314         $vol->label( '__SYSTEM_TMP_'.time) if $label;
1315
1316         $vol->creator($editor->requestor->id);
1317         $vol->create_date('now');
1318         $vol->clear_id;
1319
1320         $evt = $editor->create_asset_call_number($vol);
1321         return $evt if $evt;
1322         $vol->id($editor->lastid);
1323
1324
1325         if($label) {
1326                 # now restore the label and merge into the existing record
1327                 $vol->label($label);
1328                 (undef, $evt) = 
1329                         OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
1330                 return $evt if $evt;
1331         }
1332
1333         return undef;
1334 }
1335
1336
1337
1338
1339
1340
1341 1;