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