]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Cat.pm
on marc record import, call ingest after the create xact has been committed
[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 OpenILS::Application;
5 use OpenILS::Application::Cat::Merge;
6 use OpenILS::Application::Cat::Authority;
7 use OpenILS::Application::Cat::BibCommon;
8 use OpenILS::Application::Cat::AssetCommon;
9 use base qw/OpenILS::Application/;
10 use Time::HiRes qw(time);
11 use OpenSRF::EX qw(:try);
12 use OpenSRF::Utils::JSON;
13 use OpenILS::Utils::Fieldmapper;
14 use OpenILS::Event;
15 use OpenILS::Const qw/:const/;
16
17 use XML::LibXML;
18 use Unicode::Normalize;
19 use Data::Dumper;
20 use OpenILS::Utils::FlatXML;
21 use OpenILS::Utils::CStoreEditor q/:funcs/;
22 use OpenILS::Perm;
23 use OpenSRF::Utils::SettingsClient;
24 use OpenSRF::Utils::Logger qw($logger);
25 use OpenSRF::AppSession;
26
27 my $U = "OpenILS::Application::AppUtils";
28 my $conf;
29 my %marctemplates;
30
31 __PACKAGE__->register_method(
32         method  => "retrieve_marc_template",
33         api_name        => "open-ils.cat.biblio.marc_template.retrieve",
34         notes           => <<"  NOTES");
35         Returns a MARC 'record tree' based on a set of pre-defined templates.
36         Templates include : book
37         NOTES
38
39 sub retrieve_marc_template {
40         my( $self, $client, $type ) = @_;
41         return $marctemplates{$type} if defined($marctemplates{$type});
42         $marctemplates{$type} = _load_marc_template($type);
43         return $marctemplates{$type};
44 }
45
46 __PACKAGE__->register_method(
47         method => 'fetch_marc_template_types',
48         api_name => 'open-ils.cat.marc_template.types.retrieve'
49 );
50
51 my $marc_template_files;
52
53 sub fetch_marc_template_types {
54         my( $self, $conn ) = @_;
55         __load_marc_templates();
56         return [ keys %$marc_template_files ];
57 }
58
59 sub __load_marc_templates {
60         return if $marc_template_files;
61         if(!$conf) { $conf = OpenSRF::Utils::SettingsClient->new; }
62
63         $marc_template_files = $conf->config_value(                                     
64                 "apps", "open-ils.cat","app_settings", "marctemplates" );
65
66         $logger->info("Loaded marc templates: " . Dumper($marc_template_files));
67 }
68
69 sub _load_marc_template {
70         my $type = shift;
71
72         __load_marc_templates();
73
74         my $template = $$marc_template_files{$type};
75         open( F, $template ) or 
76                 throw OpenSRF::EX::ERROR ("Unable to open MARC template file: $template : $@");
77
78         my @xml = <F>;
79         close(F);
80         my $xml = join('', @xml);
81
82         return XML::LibXML->new->parse_string($xml)->documentElement->toString;
83 }
84
85
86
87 __PACKAGE__->register_method(
88         method => 'fetch_bib_sources',
89         api_name => 'open-ils.cat.bib_sources.retrieve.all');
90
91 sub fetch_bib_sources {
92         return OpenILS::Application::Cat::BibCommon->fetch_bib_sources();
93 }
94
95 __PACKAGE__->register_method(
96         method  => "create_record_xml",
97         api_name        => "open-ils.cat.biblio.record.xml.create.override",
98         signature       => q/@see open-ils.cat.biblio.record.xml.create/);
99
100 __PACKAGE__->register_method(
101         method          => "create_record_xml",
102         api_name                => "open-ils.cat.biblio.record.xml.create",
103         signature       => q/
104                 Inserts a new biblio with the given XML
105         /
106 );
107
108 sub create_record_xml {
109         my( $self, $client, $login, $xml, $source ) = @_;
110
111         my $override = 1 if $self->api_name =~ /override/;
112
113         my( $user_obj, $evt ) = $U->checksesperm($login, 'CREATE_MARC');
114         return $evt if $evt;
115
116         $logger->activity("user ".$user_obj->id." creating new MARC record");
117
118         my $meth = $self->method_lookup("open-ils.cat.biblio.record.xml.import");
119
120         $meth = $self->method_lookup(
121                 "open-ils.cat.biblio.record.xml.import.override") if $override;
122
123         my ($s) = $meth->run($login, $xml, $source);
124         return $s;
125 }
126
127
128
129 __PACKAGE__->register_method(
130         method  => "biblio_record_replace_marc",
131         api_name        => "open-ils.cat.biblio.record.xml.update",
132         argc            => 3, 
133         signature       => q/
134                 Updates the XML for a given biblio record.
135                 This does not change any other aspect of the record entry
136                 exception the XML, the editor, and the edit date.
137                 @return The update record object
138         /
139 );
140
141 __PACKAGE__->register_method(
142         method          => 'biblio_record_replace_marc',
143         api_name                => 'open-ils.cat.biblio.record.marc.replace',
144         signature       => q/
145                 @param auth The authtoken
146                 @param recid The record whose MARC we're replacing
147                 @param newxml The new xml to use
148         /
149 );
150
151 __PACKAGE__->register_method(
152         method          => 'biblio_record_replace_marc',
153         api_name                => 'open-ils.cat.biblio.record.marc.replace.override',
154         signature       => q/@see open-ils.cat.biblio.record.marc.replace/
155 );
156
157 sub biblio_record_replace_marc  {
158         my( $self, $conn, $auth, $recid, $newxml, $source ) = @_;
159         my $e = new_editor(authtoken=>$auth, xact=>1);
160         return $e->die_event unless $e->checkauth;
161         return $e->die_event unless $e->allowed('CREATE_MARC', $e->requestor->ws_ou);
162
163     my $no_ingest = 1;
164     my $fix_tcn = $self->api_name =~ /replace/o;
165     my $override = $self->api_name =~ /override/o;
166
167     my $res = OpenILS::Application::Cat::BibCommon->biblio_record_replace_marc(
168         $e, $recid, $newxml, $source, $fix_tcn, $override, $no_ingest);
169
170     $e->commit unless $U->event_code($res);
171
172     my $ses = OpenSRF::AppSession->create('open-ils.ingest');
173     $ses->request('open-ils.ingest.full.biblio.record', $recid);
174
175     return $res;
176 }
177
178 __PACKAGE__->register_method(
179         method  => "update_biblio_record_entry",
180         api_name        => "open-ils.cat.biblio.record_entry.update",
181     signature => q/
182         Updates a biblio.record_entry
183         @param auth The authtoken
184         @param record The record with updated values
185         @return 1 on success, Event on error.
186     /
187 );
188
189 sub update_biblio_record_entry {
190     my($self, $conn, $auth, $record) = @_;
191     my $e = new_editor(authtoken=>$auth, xact=>1);
192     return $e->die_event unless $e->checkauth;
193     return $e->die_event unless $e->allowed('UPDATE_RECORD');
194     $e->update_biblio_record_entry($record) or return $e->die_event;
195     $e->commit;
196     return 1;
197 }
198
199 __PACKAGE__->register_method(
200         method  => "undelete_biblio_record_entry",
201         api_name        => "open-ils.cat.biblio.record_entry.undelete",
202     signature => q/
203         Un-deletes a record and sets active=true
204         @param auth The authtoken
205         @param record The record_id to ressurect
206         @return 1 on success, Event on error.
207     /
208 );
209 sub undelete_biblio_record_entry {
210     my($self, $conn, $auth, $record_id) = @_;
211     my $e = new_editor(authtoken=>$auth, xact=>1);
212     return $e->die_event unless $e->checkauth;
213     return $e->die_event unless $e->allowed('UPDATE_RECORD');
214
215     my $record = $e->retrieve_biblio_record_entry($record_id)
216         or return $e->die_event;
217     $record->deleted('f');
218     $record->active('t');
219
220     # no 2 non-deleted records can have the same tcn_value
221     my $existing = $e->search_biblio_record_entry(
222         {   deleted => 'f', 
223             tcn_value => $record->tcn_value, 
224             id => {'!=' => $record_id}
225         }, {idlist => 1});
226     return OpenILS::Event->new('TCN_EXISTS') if @$existing;
227
228     $e->update_biblio_record_entry($record) or return $e->die_event;
229     $e->commit;
230     return 1;
231 }
232
233
234 __PACKAGE__->register_method(
235         method  => "biblio_record_xml_import",
236         api_name        => "open-ils.cat.biblio.record.xml.import.override",
237         signature       => q/@see open-ils.cat.biblio.record.xml.import/);
238
239 __PACKAGE__->register_method(
240         method  => "biblio_record_xml_import",
241         api_name        => "open-ils.cat.biblio.record.xml.import",
242         notes           => <<"  NOTES");
243         Takes a marcxml record and imports the record into the database.  In this
244         case, the marcxml record is assumed to be a complete record (i.e. valid
245         MARC).  The title control number is taken from (whichever comes first)
246         tags 001, 039[ab], 020a, 022a, 010, 035a and whichever does not already exist
247         in the database.
248         user_session must have IMPORT_MARC permissions
249         NOTES
250
251
252 sub biblio_record_xml_import {
253         my( $self, $client, $authtoken, $xml, $source, $auto_tcn) = @_;
254     my $e = new_editor(xact=>1, authtoken=>$authtoken);
255     return $e->die_event unless $e->checkauth;
256     return $e->die_event unless $e->allowed('IMPORT_MARC', $e->requestor->ws_ou);
257
258     my $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
259         $e, $xml, $source, $auto_tcn, $self->api_name =~ /override/, 1);
260
261     return $record if $U->event_code($record);
262
263     $e->commit;
264
265     my $ses = OpenSRF::AppSession->create('open-ils.ingest');
266     $ses->request('open-ils.ingest.full.biblio.record', $record->id);
267
268     return $record;
269 }
270
271 __PACKAGE__->register_method(
272         method  => "biblio_record_record_metadata",
273         api_name        => "open-ils.cat.biblio.record.metadata.retrieve",
274     authoritative => 1,
275         argc            => 1, #(session_id, biblio_tree ) 
276         notes           => "Walks the tree and commits any changed nodes " .
277                                         "adds any new nodes, and deletes any deleted nodes",
278 );
279
280 sub biblio_record_record_metadata {
281         my( $self, $client, $authtoken, $ids ) = @_;
282
283         return [] unless $ids and @$ids;
284
285         my $editor = new_editor(authtoken => $authtoken);
286         return $editor->event unless $editor->checkauth;
287         return $editor->event unless $editor->allowed('VIEW_USER');
288
289         my @results;
290
291         for(@$ids) {
292                 return $editor->event unless 
293                         my $rec = $editor->retrieve_biblio_record_entry($_);
294                 $rec->creator($editor->retrieve_actor_user($rec->creator));
295                 $rec->editor($editor->retrieve_actor_user($rec->editor));
296                 $rec->clear_marc; # slim the record down
297                 push( @results, $rec );
298         }
299
300         return \@results;
301 }
302
303
304
305 __PACKAGE__->register_method(
306         method  => "biblio_record_marc_cn",
307         api_name        => "open-ils.cat.biblio.record.marc_cn.retrieve",
308         argc            => 1, #(bib id ) 
309 );
310
311 sub biblio_record_marc_cn {
312         my( $self, $client, $id ) = @_;
313
314         my $session = OpenSRF::AppSession->create("open-ils.cstore");
315         my $marc = $session
316                 ->request("open-ils.cstore.direct.biblio.record_entry.retrieve", $id )
317                 ->gather(1)
318                 ->marc;
319
320         my $doc = XML::LibXML->new->parse_string($marc);
321         $doc->documentElement->setNamespace( "http://www.loc.gov/MARC21/slim", "marc", 1 );
322         
323         my @res;
324         for my $tag ( qw/050 055 060 070 080 082 086 088 090 092 096 098 099/ ) {
325                 my @node = $doc->findnodes("//marc:datafield[\@tag='$tag']");
326                 for my $x (@node) {
327                         my $cn = $x->findvalue("marc:subfield[\@code='a' or \@code='b']");
328                         push @res, {$tag => $cn} if ($cn);
329                 }
330         }
331
332         return \@res
333 }
334
335
336 __PACKAGE__->register_method(
337         method  => "orgs_for_title",
338     authoritative => 1,
339         api_name        => "open-ils.cat.actor.org_unit.retrieve_by_title"
340 );
341
342 sub orgs_for_title {
343         my( $self, $client, $record_id ) = @_;
344
345         my $vols = $U->simple_scalar_request(
346                 "open-ils.cstore",
347                 "open-ils.cstore.direct.asset.call_number.search.atomic",
348                 { record => $record_id, deleted => 'f' });
349
350         my $orgs = { map {$_->owning_lib => 1 } @$vols };
351         return [ keys %$orgs ];
352 }
353
354
355 __PACKAGE__->register_method(
356         method  => "retrieve_copies",
357     authoritative => 1,
358         api_name        => "open-ils.cat.asset.copy_tree.retrieve");
359
360 __PACKAGE__->register_method(
361         method  => "retrieve_copies",
362         api_name        => "open-ils.cat.asset.copy_tree.global.retrieve");
363
364 # user_session may be null/undef
365 sub retrieve_copies {
366
367         my( $self, $client, $user_session, $docid, @org_ids ) = @_;
368
369         if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
370
371         $docid = "$docid";
372
373         # grabbing copy trees should be available for everyone..
374         if(!@org_ids and $user_session) {
375         my($user_obj, $evt) = OpenILS::Application::AppUtils->checkses($user_session); 
376         return $evt if $evt;
377         @org_ids = ($user_obj->home_ou);
378         }
379
380         if( $self->api_name =~ /global/ ) {
381                 return _build_volume_list( { record => $docid, deleted => 'f', label => { '<>' => '##URI##' } } );
382
383         } else {
384
385                 my @all_vols;
386                 for my $orgid (@org_ids) {
387                         my $vols = _build_volume_list( 
388                                         { record => $docid, owning_lib => $orgid, deleted => 'f', label => { '<>' => '##URI##' } } );
389                         push( @all_vols, @$vols );
390                 }
391                 
392                 return \@all_vols;
393         }
394
395         return undef;
396 }
397
398
399 sub _build_volume_list {
400         my $search_hash = shift;
401
402         $search_hash->{deleted} = 'f';
403         my $e = new_editor();
404
405         my $vols = $e->search_asset_call_number($search_hash);
406
407         my @volumes;
408
409         for my $volume (@$vols) {
410
411                 my $copies = $e->search_asset_copy(
412                         { call_number => $volume->id , deleted => 'f' });
413
414                 $copies = [ sort { $a->barcode cmp $b->barcode } @$copies  ];
415
416                 for my $c (@$copies) {
417                         if( $c->status == OILS_COPY_STATUS_CHECKED_OUT ) {
418                                 $c->circulations(
419                                         $e->search_action_circulation(
420                                                 [
421                                                         { target_copy => $c->id },
422                                                         {
423                                                                 order_by => { circ => 'xact_start desc' },
424                                                                 limit => 1
425                                                         }
426                                                 ]
427                                         )
428                                 )
429                         }
430                 }
431
432                 $volume->copies($copies);
433                 push( @volumes, $volume );
434         }
435
436         #$session->disconnect();
437         return \@volumes;
438
439 }
440
441
442 __PACKAGE__->register_method(
443         method  => "fleshed_copy_update",
444         api_name        => "open-ils.cat.asset.copy.fleshed.batch.update",);
445
446 __PACKAGE__->register_method(
447         method  => "fleshed_copy_update",
448         api_name        => "open-ils.cat.asset.copy.fleshed.batch.update.override",);
449
450
451 sub fleshed_copy_update {
452         my( $self, $conn, $auth, $copies, $delete_stats ) = @_;
453         return 1 unless ref $copies;
454         my( $reqr, $evt ) = $U->checkses($auth);
455         return $evt if $evt;
456         my $editor = new_editor(requestor => $reqr, xact => 1);
457         my $override = $self->api_name =~ /override/;
458     my $retarget_holds = [];
459         $evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
460         $editor, $override, undef, $copies, $delete_stats, $retarget_holds);
461
462         if( $evt ) { 
463                 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
464                 $editor->rollback; 
465                 return $evt; 
466         }
467
468         $editor->commit;
469         $logger->info("fleshed copy update successfully updated ".scalar(@$copies)." copies");
470     reset_hold_list($auth, $retarget_holds);
471
472         return 1;
473 }
474
475 sub reset_hold_list {
476     my($auth, $hold_ids) = @_;
477     return unless @$hold_ids;
478     $logger->info("reseting holds after copy status change: @$hold_ids");
479     my $ses = OpenSRF::AppSession->create('open-ils.circ');
480     $ses->request('open-ils.circ.hold.reset.batch', $auth, $hold_ids);
481 }
482
483
484 __PACKAGE__->register_method(
485         method => 'in_db_merge',
486         api_name        => 'open-ils.cat.biblio.records.merge',
487         signature       => q/
488                 Merges a group of records
489                 @param auth The login session key
490                 @param master The id of the record all other records should be merged into
491                 @param records Array of records to be merged into the master record
492                 @return 1 on success, Event on error.
493         /
494 );
495
496 sub in_db_merge {
497         my( $self, $conn, $auth, $master, $records ) = @_;
498
499         my $editor = new_editor( authtoken => $auth, xact => 1 );
500     return $editor->die_event unless $editor->checkauth;
501     return $editor->die_event unless $editor->allowed('MERGE_BIB_RECORDS'); # TODO see below about record ownership
502
503     my $count = 0;
504     for my $source ( @$records ) {
505         #XXX we actually /will/ want to check perms for master and sources after record ownership exists
506
507         # This stored proc (asset.merge_record_assets(target,source)) has the side effects of
508         # moving call_number, title-type (and some volume-type) hold_request and uri-mapping
509         # objects from the source record to the target record, so must be called from within
510         # a transaction.
511
512         $count += $editor->json_query({
513             select => {
514                 bre => [{
515                     alias => 'count',
516                     transform => 'asset.merge_record_assets',
517                     column => 'id',
518                     params => [$source]
519                 }]
520             },
521             from   => 'bre',
522             where  => { id => $master }
523         })->[0]->{count}; # count of objects moved, of all types
524
525     }
526
527         $editor->commit;
528     return $count;
529 }
530
531
532 __PACKAGE__->register_method(
533         method  => "fleshed_volume_update",
534         api_name        => "open-ils.cat.asset.volume.fleshed.batch.update",);
535
536 __PACKAGE__->register_method(
537         method  => "fleshed_volume_update",
538         api_name        => "open-ils.cat.asset.volume.fleshed.batch.update.override",);
539
540 sub fleshed_volume_update {
541         my( $self, $conn, $auth, $volumes, $delete_stats ) = @_;
542         my( $reqr, $evt ) = $U->checkses($auth);
543         return $evt if $evt;
544
545         my $override = ($self->api_name =~ /override/);
546         my $editor = new_editor( requestor => $reqr, xact => 1 );
547     my $retarget_holds = [];
548
549         for my $vol (@$volumes) {
550                 $logger->info("vol-update: investigating volume ".$vol->id);
551
552                 $vol->editor($reqr->id);
553                 $vol->edit_date('now');
554
555                 my $copies = $vol->copies;
556                 $vol->clear_copies;
557
558                 $vol->editor($editor->requestor->id);
559                 $vol->edit_date('now');
560
561                 if( $vol->isdeleted ) {
562
563                         $logger->info("vol-update: deleting volume");
564                         my $cs = $editor->search_asset_copy(
565                                 { call_number => $vol->id, deleted => 'f' } );
566                         return OpenILS::Event->new(
567                                 'VOLUME_NOT_EMPTY', payload => $vol->id ) if @$cs;
568
569                         $vol->deleted('t');
570                         return $editor->event unless
571                                 $editor->update_asset_call_number($vol);
572
573                         
574                 } elsif( $vol->isnew ) {
575                         $logger->info("vol-update: creating volume");
576                         $evt = OpenILS::Application::Cat::AssetCommon->create_volume( $override, $editor, $vol );
577                         return $evt if $evt;
578
579                 } elsif( $vol->ischanged ) {
580                         $logger->info("vol-update: update volume");
581                         $evt = update_volume($vol, $editor);
582                         return $evt if $evt;
583                 }
584
585                 # now update any attached copies
586                 if( $copies and @$copies and !$vol->isdeleted ) {
587                         $_->call_number($vol->id) for @$copies;
588                         $evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
589                 $editor, $override, $vol, $copies, $delete_stats, $retarget_holds);
590                         return $evt if $evt;
591                 }
592         }
593
594         $editor->finish;
595     reset_hold_list($auth, $retarget_holds);
596         return scalar(@$volumes);
597 }
598
599
600 sub update_volume {
601         my $vol = shift;
602         my $editor = shift;
603         my $evt;
604
605         return $evt if ( $evt = OpenILS::Application::Cat::AssetCommon->org_cannot_have_vols($editor, $vol->owning_lib) );
606
607         my $vols = $editor->search_asset_call_number( { 
608                         owning_lib      => $vol->owning_lib,
609                         record          => $vol->record,
610                         label                   => $vol->label,
611                         deleted         => 'f'
612                 }
613         );
614
615         # There exists a different volume in the DB with the same properties
616         return OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
617                 if grep { $_->id ne $vol->id } @$vols;
618
619         return $editor->event unless $editor->update_asset_call_number($vol);
620         return undef;
621 }
622
623
624
625 __PACKAGE__->register_method (
626         method => 'delete_bib_record',
627         api_name => 'open-ils.cat.biblio.record_entry.delete');
628
629 sub delete_bib_record {
630     my($self, $conn, $auth, $rec_id) = @_;
631     my $e = new_editor(xact=>1, authtoken=>$auth);
632     return $e->die_event unless $e->checkauth;
633     return $e->die_event unless $e->allowed('DELETE_RECORD', $e->requestor->ws_ou);
634     my $vols = $e->search_asset_call_number({record=>$rec_id, deleted=>'f'});
635     return OpenILS::Event->new('RECORD_NOT_EMPTY', payload=>$rec_id) if @$vols;
636     my $evt = OpenILS::Application::Cat::BibCommon->delete_rec($e, $rec_id);
637     if($evt) { $e->rollback; return $evt; }   
638     $e->commit;
639     return 1;
640 }
641
642
643
644 __PACKAGE__->register_method (
645         method => 'batch_volume_transfer',
646         api_name => 'open-ils.cat.asset.volume.batch.transfer',
647 );
648
649 __PACKAGE__->register_method (
650         method => 'batch_volume_transfer',
651         api_name => 'open-ils.cat.asset.volume.batch.transfer.override',
652 );
653
654
655 sub batch_volume_transfer {
656         my( $self, $conn, $auth, $args ) = @_;
657
658         my $evt;
659         my $rec         = $$args{docid};
660         my $o_lib       = $$args{lib};
661         my $vol_ids = $$args{volumes};
662
663         my $override = 1 if $self->api_name =~ /override/;
664
665         $logger->info("merge: transferring volumes to lib=$o_lib and record=$rec");
666
667         my $e = new_editor(authtoken => $auth, xact =>1);
668         return $e->event unless $e->checkauth;
669         return $e->event unless $e->allowed('UPDATE_VOLUME', $o_lib);
670
671         my $dorg = $e->retrieve_actor_org_unit($o_lib)
672                 or return $e->event;
673
674         my $ou_type = $e->retrieve_actor_org_unit_type($dorg->ou_type)
675                 or return $e->event;
676
677         return $evt if ( $evt = OpenILS::Application::Cat::AssetCommon->org_cannot_have_vols($e, $o_lib) );
678
679         my $vols = $e->batch_retrieve_asset_call_number($vol_ids);
680         my @seen;
681
682    my @rec_ids;
683
684         for my $vol (@$vols) {
685
686         # if we've already looked at this volume, go to the next
687         next if !$vol or grep { $vol->id == $_ } @seen;
688
689                 # grab all of the volumes in the list that have 
690                 # the same label so they can be merged
691                 my @all = grep { $_->label eq $vol->label } @$vols;
692
693                 # take note of the fact that we've looked at this set of volumes
694                 push( @seen, $_->id ) for @all;
695         push( @rec_ids, $_->record ) for @all;
696
697                 # for each volume, see if there are any copies that have a 
698                 # remote circ_lib (circ_lib != vol->owning_lib and != $o_lib ).  
699                 # if so, warn them
700                 unless( $override ) {
701                         for my $v (@all) {
702
703                                 $logger->debug("merge: searching for copies with remote circ_lib for volume ".$v->id);
704                                 my $args = { 
705                                         call_number     => $v->id, 
706                                         circ_lib                => { "not in" => [ $o_lib, $v->owning_lib ] },
707                                         deleted         => 'f'
708                                 };
709
710                                 my $copies = $e->search_asset_copy($args, {idlist=>1});
711
712                                 # if the copy's circ_lib matches the destination lib,
713                                 # that's ok too
714                                 return OpenILS::Event->new('COPY_REMOTE_CIRC_LIB') if @$copies;
715                         }
716                 }
717
718                 # see if there is a volume at the destination lib that 
719                 # already has the requested label
720                 my $existing_vol = $e->search_asset_call_number(
721                         {
722                                 label                   => $vol->label, 
723                                 record          =>$rec, 
724                                 owning_lib      =>$o_lib,
725                                 deleted         => 'f'
726                         }
727                 )->[0];
728
729                 if( $existing_vol ) {
730
731                         if( grep { $_->id == $existing_vol->id } @all ) {
732                                 # this volume is already accounted for in our list of volumes to merge
733                                 $existing_vol = undef;
734
735                         } else {
736                                 # this volume exists on the destination record/owning_lib and must
737                                 # be used as the destination for merging
738                                 $logger->debug("merge: volume already exists at destination record: ".
739                                         $existing_vol->id.' : '.$existing_vol->label) if $existing_vol;
740                         }
741                 } 
742
743                 if( @all > 1 || $existing_vol ) {
744                         $logger->info("merge: found collisions in volume transfer");
745                         my @args = ($e, \@all);
746                         @args = ($e, \@all, $existing_vol) if $existing_vol;
747                         ($vol, $evt) = OpenILS::Application::Cat::Merge::merge_volumes(@args);
748                         return $evt if $evt;
749                 } 
750                 
751                 if( !$existing_vol ) {
752
753                         $vol->owning_lib($o_lib);
754                         $vol->record($rec);
755                         $vol->editor($e->requestor->id);
756                         $vol->edit_date('now');
757         
758                         $logger->info("merge: updating volume ".$vol->id);
759                         $e->update_asset_call_number($vol) or return $e->event;
760
761                 } else {
762                         $logger->info("merge: bypassing volume update because existing volume used as target");
763                 }
764
765                 # regardless of what volume was used as the destination, 
766                 # update any copies that have moved over to the new lib
767                 my $copies = $e->search_asset_copy({call_number=>$vol->id, deleted => 'f'});
768
769                 # update circ lib on the copies - make this a method flag?
770                 for my $copy (@$copies) {
771                         next if $copy->circ_lib == $o_lib;
772                         $logger->info("merge: transfer moving circ lib on copy ".$copy->id);
773                         $copy->circ_lib($o_lib);
774                         $copy->editor($e->requestor->id);
775                         $copy->edit_date('now');
776                         $e->update_asset_copy($copy) or return $e->event;
777                 }
778
779                 # Now see if any empty records need to be deleted after all of this
780
781         for(@rec_ids) {
782             $logger->debug("merge: seeing if we should delete record $_...");
783             $evt = OpenILS::Application::Cat::BibCommon->delete_rec($e, $_) 
784                 if OpenILS::Application::Cat::BibCommon->title_is_empty($e, $_);
785             return $evt if $evt;
786         }
787         }
788
789         $logger->info("merge: transfer succeeded");
790         $e->commit;
791         return 1;
792 }
793
794
795
796
797 __PACKAGE__->register_method(
798         api_name => 'open-ils.cat.call_number.find_or_create',
799         method => 'find_or_create_volume',
800 );
801
802 sub find_or_create_volume {
803         my( $self, $conn, $auth, $label, $record_id, $org_id ) = @_;
804         my $e = new_editor(authtoken=>$auth, xact=>1);
805         return $e->die_event unless $e->checkauth;
806     my ($vol, $evt, $exists) = 
807         OpenILS::Application::Cat::AssetCommon->find_or_create_volume($e, $label, $record_id, $org_id);
808     return $evt if $evt;
809     $e->rollback if $exists;
810     $e->commit if $vol;
811     return $vol->id;
812 }
813
814
815 __PACKAGE__->register_method(
816         method  => "create_serial_record_xml",
817         api_name        => "open-ils.cat.serial.record.xml.create.override",
818         signature       => q/@see open-ils.cat.serial.record.xml.create/);
819
820 __PACKAGE__->register_method(
821         method          => "create_serial_record_xml",
822         api_name                => "open-ils.cat.serial.record.xml.create",
823         signature       => q/
824                 Inserts a new serial record with the given XML
825         /
826 );
827
828 sub create_serial_record_xml {
829         my( $self, $client, $login, $source, $owning_lib, $record_id, $xml ) = @_;
830
831         my $override = 1 if $self->api_name =~ /override/; # not currently used
832
833         my $e = new_editor(xact=>1, authtoken=>$login);
834         return $e->die_event unless $e->checkauth;
835         return $e->die_event unless $e->allowed('CREATE_MFHD_RECORD', $owning_lib);
836
837         # Auto-populate the location field of a placeholder MFHD record with the library name
838         my $aou = $e->retrieve_actor_org_unit($owning_lib) or return $e->die_event;
839
840         my $mfhd = Fieldmapper::serial::record_entry->new;
841
842         $mfhd->source($source) if $source;
843         $mfhd->record($record_id);
844         $mfhd->creator($e->requestor->id);
845         $mfhd->editor($e->requestor->id);
846         $mfhd->create_date('now');
847         $mfhd->edit_date('now');
848         $mfhd->owning_lib($owning_lib);
849
850         # If the caller did not pass in MFHD XML, create a placeholder record.
851         # The placeholder will only contain the name of the owning library.
852         # The goal is to generate common patterns for the caller in the UI that
853         # then get passed in here.
854         if (!$xml) {
855                 $xml = "<record xsi:schemaLocation=\"http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.loc.gov/MARC21/slim\"> <leader>00307cy  a22001094  4500</leader> <controlfield tag=\"001\">42153</controlfield> <controlfield tag=\"005\">20090601182414.0</controlfield> <controlfield tag=\"008\">051011                eng 090309</controlfield> <datafield tag=\"852\" ind1=\" \" ind2=\" \"> <subfield code=\"b\">" . $aou->name . "</subfield> </datafield></record>";
856         }
857         my $marcxml = XML::LibXML->new->parse_string($xml);
858         $marcxml->documentElement->setNamespace("http://www.loc.gov/MARC21/slim", "marc", 1 );
859         $marcxml->documentElement->setNamespace("http://www.loc.gov/MARC21/slim");
860
861         $mfhd->marc($U->entityize($marcxml->documentElement->toString));
862
863         $e->create_serial_record_entry($mfhd) or return $e->die_event;
864
865         $e->commit;
866         return $mfhd->id;
867 }
868
869 1;