]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Cat/AssetCommon.pm
LP 2061136 toward perm and hold cancel omnibus
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Cat / AssetCommon.pm
1 package OpenILS::Application::Cat::AssetCommon;
2 use strict; use warnings;
3 use OpenILS::Application::Cat::BibCommon;
4 use OpenILS::Utils::CStoreEditor q/:funcs/;
5 use OpenSRF::Utils::Logger qw($logger);
6 use OpenILS::Application::Cat::Merge;
7 use OpenILS::Application::AppUtils;
8 use OpenILS::Utils::Fieldmapper;
9 use OpenILS::Const qw/:const/;
10 use OpenSRF::AppSession;
11 use OpenILS::Event;
12 use OpenILS::Utils::Penalty;
13 use OpenILS::Application::Circ::CircCommon;
14 my $U = 'OpenILS::Application::AppUtils';
15
16
17 # ---------------------------------------------------------------------------
18 # Shared copy mangling code.  Do not publish methods from here.
19 # ---------------------------------------------------------------------------
20
21 sub org_cannot_have_vols {
22     my($class, $e, $org_id) = @_;
23     my $org = $e->retrieve_actor_org_unit([
24         $org_id,
25         {   flesh => 1,
26             flesh_fields => {aou => ['ou_type']}
27         }]) or return $e->event;
28
29     return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
30         unless $U->is_true($org->ou_type->can_have_vols);
31
32     return 0;
33 }
34
35 sub fix_copy_price {
36     my $class = shift;
37     my $copy = shift;
38
39     if(defined $copy->price) {
40         my $p = $copy->price || 0;
41         $p =~ s/\$//og;
42         $copy->price($p);
43     }
44
45     my $d = $copy->deposit_amount || 0;
46     $d =~ s/\$//og;
47     $copy->deposit_amount($d);
48 }
49
50 sub create_copy {
51     my($class, $editor, $vol, $copy) = @_;
52
53     return $editor->event unless
54         $editor->allowed('CREATE_COPY', $class->copy_perm_org($vol, $copy));
55
56     my $existing = $editor->search_asset_copy(
57         { barcode => $copy->barcode, deleted => 'f' } );
58     
59     return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
60
61     my $copy_loc = $editor->search_asset_copy_location(
62         { id => $copy->location, deleted => 'f' } );
63         
64     return OpenILS::Event->new('COPY_LOCATION_NOT_FOUND') unless @$copy_loc;
65     
66    # see if the volume this copy references is marked as deleted
67     return OpenILS::Event->new('VOLUME_DELETED', vol => $vol->id) 
68         if $U->is_true($vol->deleted);
69
70     my $evt;
71     my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
72     return $evt if ($evt = $class->org_cannot_have_vols($editor, $org));
73
74     $copy->clear_id;
75     $copy->editor($editor->requestor->id);
76     $copy->creator($editor->requestor->id);
77     $copy->create_date('now');
78     $copy->call_number($vol->id);
79     $class->fix_copy_price($copy);
80
81     my $cp = $editor->create_asset_copy($copy) or return $editor->die_event;
82     $copy->id($cp->id);
83     return undef;
84 }
85
86
87 # 'delete_stats' is somewhat of a misnomer.  With no flags set, this method
88 # still deletes any existing maps not represented in $copy->stat_cat_entries,
89 # but aborts when $copy->stat_cat_entries is empty or undefined.  If
90 # 'delete_stats' is true, this method will delete all the maps when
91 # $copy->stat_cat_entries is empty or undefined.
92 #
93 # The 'add_or_update_only' flag is more straightforward.  It adds missing
94 # maps, updates present maps with any new values, and leaves the rest
95 # alone.
96 sub update_copy_stat_entries {
97     my($class, $editor, $copy, $delete_stats, $add_or_update_only) = @_;
98
99     return undef if $copy->isdeleted;
100     return undef unless $copy->ischanged or $copy->isnew;
101
102     my $evt;
103     my $entries = $copy->stat_cat_entries;
104
105     if( $delete_stats ) {
106         $entries = ($entries and @$entries) ? $entries : [];
107     } else {
108         return undef unless ($entries and @$entries);
109     }
110
111     my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
112
113     if(!$copy->isnew) {
114         # if there is no stat cat entry on the copy who's id matches the
115         # current map's id, remove the map from the database
116         for my $map (@$maps) {
117             if (!$add_or_update_only) {
118                 if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
119
120                     $logger->info("copy update found stale ".
121                         "stat cat entry map ".$map->id. " on copy ".$copy->id);
122
123                     $editor->delete_asset_stat_cat_entry_copy_map($map)
124                         or return $editor->event;
125                 }
126             } else {
127                 if( grep { $_->stat_cat == $map->stat_cat and $_->id != $map->stat_cat_entry } @$entries ) {
128
129                     $logger->info("copy update found ".
130                         "stat cat entry map ".$map->id. " needing update on copy ".$copy->id);
131
132                     $editor->delete_asset_stat_cat_entry_copy_map($map)
133                         or return $editor->event;
134                 }
135             }
136         }
137     }
138
139     # go through the stat cat update/create process
140     for my $entry (@$entries) { 
141         next unless $entry;
142
143         # if this link already exists in the DB, don't attempt to re-create it
144         next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
145     
146         my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
147
148         my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
149         
150         $new_map->stat_cat( $sc );
151         $new_map->stat_cat_entry( $entry->id );
152         $new_map->owning_copy( $copy->id );
153
154         $editor->create_asset_stat_cat_entry_copy_map($new_map)
155             or return $editor->event;
156
157         $logger->info("copy update created new stat cat entry map ".$editor->data);
158     }
159
160     return undef;
161 }
162
163 # if 'delete_maps' is true, the copy->parts data is  treated as the
164 # authoritative list for the copy. existing part maps not targeting
165 # these parts will be deleted from the DB
166 sub update_copy_parts {
167     my($class, $editor, $copy, $delete_maps, $create_parts) = @_;
168
169     return undef if $copy->isdeleted;
170     return undef unless $copy->ischanged or $copy->isnew;
171
172     my $evt;
173     my $incoming_parts = $copy->parts;
174
175     if( $delete_maps ) {
176         $incoming_parts = ($incoming_parts and @$incoming_parts) ? $incoming_parts : [];
177     } else {
178         return undef unless ($incoming_parts and @$incoming_parts);
179     }
180
181     my $maps = $editor->search_asset_copy_part_map({target_copy=>$copy->id});
182
183     if(!$copy->isnew) {
184         # if there is no part map on the copy who's id matches the
185         # current map's id, remove the map from the database
186         for my $map (@$maps) {
187             if(! grep { $_->id == $map->part } @$incoming_parts ) {
188
189                 $logger->info("copy update found stale ".
190                     "monographic part map ".$map->id. " on copy ".$copy->id);
191
192                 $editor->delete_asset_copy_part_map($map)
193                     or return $editor->event;
194             }
195         }
196     }
197
198     # go through the part map update/create process
199     for my $incoming_part (@$incoming_parts) { 
200         next unless $incoming_part;
201
202         # if this link already exists in the DB, don't attempt to re-create it
203         next if( grep{$_->part == $incoming_part->id} @$maps );
204
205         if ($incoming_part->isnew) {
206             next unless $create_parts;
207             my $new_part = Fieldmapper::biblio::monograph_part->new();
208             $new_part->record( $incoming_part->record );
209             $new_part->label( $incoming_part->label );
210             $incoming_part = $editor->create_biblio_monograph_part($new_part)
211                 or return $editor->event;
212         }
213     
214         my $new_map = Fieldmapper::asset::copy_part_map->new();
215
216         $new_map->part( $incoming_part->id );
217         $new_map->target_copy( $copy->id );
218
219         $editor->create_asset_copy_part_map($new_map)
220             or return $editor->event;
221
222         $logger->info("copy update created new monographic part copy map ".$editor->data);
223     }
224
225     return undef;
226 }
227
228
229
230 sub update_copy_notes {
231     my($class, $editor, $copy) = @_;
232
233     return undef if $copy->isdeleted;
234
235     my $evt;
236     my $incoming_notes = $copy->notes;
237
238     for my $incoming_note (@$incoming_notes) { 
239         next unless $incoming_note;
240
241         if ($incoming_note->isnew) {
242             next if ($incoming_note->isdeleted); # if it was added and deleted in the same session
243
244             my $new_note = Fieldmapper::asset::copy_note->new();
245             $new_note->owning_copy( $copy->id );
246             $new_note->pub( $incoming_note->pub );
247             $new_note->title( $incoming_note->title );
248             $new_note->value( $incoming_note->value );
249             $new_note->creator( $incoming_note->creator || $editor->requestor->id );
250             $incoming_note = $editor->create_asset_copy_note($new_note)
251                 or return $editor->event;
252
253         } elsif ($incoming_note->ischanged) {
254             $incoming_note = $editor->update_asset_copy_note($incoming_note)
255         } elsif ($incoming_note->isdeleted) {
256             $incoming_note = $editor->delete_asset_copy_note($incoming_note)
257         }
258     
259     }
260
261     return undef;
262 }
263
264 sub update_copy_alerts {
265     my($class, $editor, $copy) = @_;
266
267     return undef if $copy->isdeleted;
268
269     my $evt;
270     my $incoming_copy_alerts = $copy->copy_alerts;
271
272     for my $incoming_copy_alert (@$incoming_copy_alerts) { 
273         next unless $incoming_copy_alert;
274
275         if ($incoming_copy_alert->isnew) {
276             next if ($incoming_copy_alert->isdeleted); # if it was added and deleted in the same session
277
278             my $new_copy_alert = Fieldmapper::asset::copy_alert->new();
279             $new_copy_alert->copy( $copy->id );
280             $new_copy_alert->temp( $incoming_copy_alert->temp );
281             $new_copy_alert->ack_time( $incoming_copy_alert->ack_time );
282             $new_copy_alert->note( $incoming_copy_alert->note );
283             $new_copy_alert->alert_type( $incoming_copy_alert->alert_type );
284             $new_copy_alert->create_staff( $incoming_copy_alert->create_staff || $editor->requestor->id );
285             $incoming_copy_alert = $editor->create_asset_copy_alert($new_copy_alert)
286                 or return $editor->event;
287         } elsif ($incoming_copy_alert->ischanged) {
288             $incoming_copy_alert = $editor->update_asset_copy_alert($incoming_copy_alert)
289         } elsif ($incoming_copy_alert->isdeleted) {
290             $incoming_copy_alert = $editor->delete_asset_copy_alert($incoming_copy_alert->id)
291         }
292     
293     }
294
295     return undef;
296 }
297
298 sub update_copy_tags {
299     my($class, $editor, $copy) = @_;
300
301     return undef if $copy->isdeleted;
302
303     my $evt;
304     my $incoming_maps = $copy->tags;
305
306     for my $incoming_map (@$incoming_maps) {
307         next unless $incoming_map;
308
309         if ($incoming_map->isnew) {
310             next if ($incoming_map->isdeleted); # if it was added and deleted in the same session
311
312             my $tag_id;
313             if ($incoming_map->tag->isnew) {
314                 my $new_tag = Fieldmapper::asset::copy_tag->new();
315                 $new_tag->owner( $incoming_map->tag->owner );
316                 $new_tag->label( $incoming_map->tag->label );
317                 $new_tag->tag_type( $incoming_map->tag->tag_type );
318                 $new_tag->pub( $incoming_map->tag->pub );
319                 my $tag = $editor->create_asset_copy_tag($new_tag)
320                     or return $editor->event;
321                 $tag_id = $tag->id;
322             } else {
323                 $tag_id = $incoming_map->tag->id;
324             }
325             my $new_map = Fieldmapper::asset::copy_tag_copy_map->new();
326             $new_map->copy( $copy->id );
327             $new_map->tag( $tag_id );
328             $incoming_map = $editor->create_asset_copy_tag_copy_map($new_map)
329                 or return $editor->event;
330
331         } elsif ($incoming_map->ischanged) {
332             $incoming_map = $editor->update_asset_copy_tag_copy_map($incoming_map)
333         } elsif ($incoming_map->isdeleted) {
334             $incoming_map = $editor->delete_asset_copy_tag_copy_map($incoming_map)
335         }
336     
337     }
338
339     return undef;
340 }
341
342 sub update_copy {
343     my($class, $editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib) = @_;
344
345     $override = { all => 1 } if($override && !ref $override);
346     $override = { all => 0 } if(!ref $override);
347
348     # Duplicated check from create_copy in case a copy template with a deleted location is applied later
349     my $copy_loc = $editor->search_asset_copy_location(
350         { id => $copy->location, deleted => 'f' } );
351         
352     return OpenILS::Event->new('COPY_LOCATION_NOT_FOUND') unless @$copy_loc;
353     
354     my $evt;
355     my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
356     return $evt if ( $evt = $class->org_cannot_have_vols($editor, $org) );
357
358     $logger->info("vol-update: updating copy ".$copy->id);
359     my $orig_copy = $editor->retrieve_asset_copy($copy->id);
360
361     # Call-number may have changed, find the original
362     my $orig_vol_id = $editor->json_query({select => {acp => ['call_number']}, from => 'acp', where => {id => $copy->id}});
363     my $orig_vol  = $editor->retrieve_asset_call_number($orig_vol_id->[0]->{call_number});
364
365     $copy->editor($editor->requestor->id);
366     $copy->edit_date('now');
367
368     $copy->age_protect( $copy->age_protect->id )
369         if ref $copy->age_protect;
370
371     $class->fix_copy_price($copy);
372     $class->check_hold_retarget($editor, $copy, $orig_copy, $retarget_holds);
373
374     return $editor->event unless $editor->update_asset_copy($copy);
375     return $class->remove_empty_objects($editor, $override, $orig_vol, $force_delete_empty_bib);
376 }
377
378 sub check_hold_retarget {
379     my($class, $editor, $copy, $orig_copy, $retarget_holds) = @_;
380     return unless $retarget_holds;
381
382     if( !($copy->isdeleted or $U->is_true($copy->deleted)) ) {
383         # see if a status change warrants a retarget
384
385         $orig_copy = $editor->retrieve_asset_copy($copy->id) unless $orig_copy;
386
387         if($orig_copy->status == $copy->status) {
388             # no status change, no retarget
389             return;
390         }
391
392         my $stat = $editor->retrieve_config_copy_status($copy->status);
393
394         # new status is holdable, no retarget. Later add logic to find potential 
395         # holds and retarget those to pick up the newly available copy
396         return if $U->is_true($stat->holdable); 
397     }
398
399     my $hold_ids = $editor->search_action_hold_request(
400         {   current_copy        => $copy->id, 
401             cancel_time         => undef, 
402             fulfillment_time    => undef 
403         }, {idlist => 1}
404     );
405
406     push(@$retarget_holds, @$hold_ids);
407 }
408
409 # TODO: get Booking.pm to use this shared method
410 sub fetch_copies_by_ids {
411     my ($class, $e, $copy_ids) = @_;
412     my $results = $e->search_asset_copy([
413         {id => $copy_ids},
414         {flesh => 1, flesh_fields => {acp => ['call_number']}}
415     ]);
416     return $results if ref($results) eq 'ARRAY';
417     return [];
418 }
419
420 # this does the actual work
421 sub update_fleshed_copies {
422     my($class, $editor, $override, $vol, $copies, $delete_stats, $retarget_holds, $force_delete_empty_bib, $create_parts) = @_;
423
424     $override = { all => 1 } if($override && !ref $override);
425     $override = { all => 0 } if(!ref $override);
426
427     my $evt;
428     my $fetchvol = ($vol) ? 0 : 1;
429
430     my %cache;
431     $cache{$vol->id} = $vol if $vol;
432
433     sub process_copy {
434         my ($original_copy, $cache_ref, $editor, $class, $logger) = @_;
435
436         my $copyid = $original_copy->id;
437         $logger->info("vol-update: inspecting copy $copyid");
438
439         my $vol;
440         if (!($vol = $cache_ref->{$original_copy->call_number})) {
441             $vol = $cache_ref->{$original_copy->call_number} =
442                 $editor->retrieve_asset_call_number($original_copy->call_number);
443             return $editor->event unless $vol;
444         }
445
446         return $editor->event unless
447             $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $original_copy));
448
449         return; # return nothing if all checks pass
450     }
451
452     my $original_copies = $class->fetch_copies_by_ids( $editor, map { $_->id } @$copies );
453     for my $original_copy (@$original_copies) {
454         my $event = process_copy($original_copy, \%cache, $editor, $class, $logger);
455         return $event if $event;
456     }
457
458     for my $copy (@$copies) {
459         my $event = process_copy($copy, \%cache, $editor, $class, $logger);
460         return $event if $event;
461
462         $copy->editor($editor->requestor->id);
463         $copy->edit_date('now');
464
465         $copy->status( $copy->status->id ) if ref($copy->status);
466         $copy->location( $copy->location->id ) if ref($copy->location);
467         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
468         
469         my $parts = $copy->parts;
470         $copy->clear_parts;
471
472         my $sc_entries = $copy->stat_cat_entries;
473         $copy->clear_stat_cat_entries;
474
475         my $notes = $copy->notes;
476         $copy->clear_notes;
477
478         my $tags = $copy->tags;
479         $copy->clear_tags;
480
481         my $copy_alerts = $copy->copy_alerts;
482         $copy->clear_copy_alerts;
483
484         if( $copy->isdeleted ) {
485             $evt = $class->delete_copy($editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib);
486             return $evt if $evt;
487
488         } elsif( $copy->isnew ) {
489             $evt = $class->create_copy( $editor, $vol, $copy );
490             return $evt if $evt;
491
492         } elsif( $copy->ischanged ) {
493
494             $evt = $class->update_copy( $editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib);
495             return $evt if $evt;
496         }
497
498         $copy->stat_cat_entries( $sc_entries );
499         $evt = $class->update_copy_stat_entries($editor, $copy, $delete_stats);
500
501         $copy->parts( $parts );
502         # probably okay to use $delete_stats here for simplicity
503         $evt = $class->update_copy_parts($editor, $copy, $delete_stats, $create_parts);
504
505         $copy->notes( $notes );
506         $evt = $class->update_copy_notes($editor, $copy);
507
508         $copy->tags( $tags );
509         $evt = $class->update_copy_tags($editor, $copy);
510
511         $copy->copy_alerts( $copy_alerts );
512         $evt = $class->update_copy_alerts($editor, $copy);
513
514         return $evt if $evt;
515     }
516
517     $logger->debug("vol-update: done updating copy batch");
518
519     return undef;
520 }
521
522
523 sub delete_copy {
524     my($class, $editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib, $skip_empty_cleanup) = @_;
525
526     return $editor->event unless
527         $editor->allowed('DELETE_COPY', $class->copy_perm_org($vol, $copy));
528
529     $override = { all => 1 } if($override && !ref $override);
530     $override = { all => 0 } if(!ref $override);
531
532     my $stat = $U->copy_status($copy->status);
533     if ($U->is_true($stat->restrict_copy_delete)) {
534         if ($override->{all} || grep { $_ eq 'COPY_DELETE_WARNING' } @{$override->{events}}) {
535             return $editor->event unless $editor->allowed('COPY_DELETE_WARNING.override', $class->copy_perm_org($vol, $copy))
536         } else {
537             return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
538         }
539     }
540
541     $logger->info("vol-update: deleting copy ".$copy->id);
542     $copy->deleted('t');
543
544     $copy->editor($editor->requestor->id);
545     $copy->edit_date('now');
546     $editor->update_asset_copy($copy) or return $editor->event;
547
548     # Cancel any open transits for this copy
549     my $transits = $editor->search_action_transit_copy(
550         { target_copy=>$copy->id, dest_recv_time => undef, cancel_time => undef } );
551
552     for my $t (@$transits) {
553         $t->cancel_time('now');
554         $editor->update_action_transit_copy($t)
555             or return $editor->event;
556     }
557
558     my $evt = $class->cancel_copy_holds($editor, $copy);
559     return $evt if $evt;
560
561     $class->check_hold_retarget($editor, $copy, undef, $retarget_holds);
562
563     return undef if $skip_empty_cleanup;
564
565     return $class->remove_empty_objects($editor, $override, $vol, $force_delete_empty_bib);
566 }
567
568
569 # deletes all holds that specifically target the deleted copy
570 sub cancel_copy_holds {
571     my($class, $editor, $copy) = @_;
572
573     my $holds = $editor->search_action_hold_request({   
574         target              => $copy->id, 
575         hold_type           => [qw/C R F/],
576         cancel_time         => undef, 
577         fulfillment_time    => undef 
578     });
579
580     return $class->cancel_hold_list($editor, $holds);
581 }
582
583 # deletes all holds that specifically target the deleted volume
584 sub cancel_volume_holds {
585     my($class, $editor, $volume) = @_;
586
587     my $holds = $editor->search_action_hold_request({   
588         target              => $volume->id, 
589         hold_type           => 'V',
590         cancel_time         => undef, 
591         fulfillment_time    => undef 
592     });
593
594     return $class->cancel_hold_list($editor, $holds);
595 }
596
597 sub cancel_hold_list {
598     my($class, $editor, $holds) = @_;
599
600     for my $hold (@$holds) {
601
602         $hold->cancel_time('now');
603         $hold->cancel_cause(1); # un-targeted expiration.  Do we need an alternate "target deleted" cause?
604         $editor->update_action_hold_request($hold) or return $editor->die_event;
605
606         # Update our copy of the hold to pick up the cancel_time
607         # before we pass it off to A/T.
608         $hold = $editor->retrieve_action_hold_request($hold->id);
609
610         # tell A/T the hold was cancelled.  Don't wait for a response..
611         my $at_ses = OpenSRF::AppSession->create('open-ils.trigger');
612         $at_ses->request(
613             'open-ils.trigger.event.autocreate',
614             'hold_request.cancel.expire_no_target', 
615             $hold, $hold->pickup_lib);
616     }
617
618     return undef;
619 }
620
621 sub test_perm_against_original_owning_lib {
622     my($class, $editor, $perm, $vid) = @_;
623     my $vol = $editor->retrieve_asset_call_number($vid) or return $editor->event;
624     return $editor->die_event unless $editor->allowed($perm, $vol->owning_lib);
625     return 1;
626 }
627
628 sub create_volume {
629     my($class, $override, $editor, $vol) = @_;
630     my $evt;
631
632     return (undef, $evt) if ( $evt = $class->org_cannot_have_vols($editor, $vol->owning_lib) );
633
634     $override = { all => 1 } if($override && !ref $override);
635     $override = { all => 0 } if(!ref $override);
636
637    # see if the record this volume references is marked as deleted
638    my $rec = $editor->retrieve_biblio_record_entry($vol->record)
639       or return $editor->die_event;
640
641     return (
642         undef, 
643         OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id)
644     ) if $U->is_true($rec->deleted);
645
646     # first lets see if there are any collisions
647     my $vols = $editor->search_asset_call_number( { 
648             owning_lib  => $vol->owning_lib,
649             record      => $vol->record,
650             label           => $vol->label,
651             prefix          => $vol->prefix,
652             suffix          => $vol->suffix,
653             deleted     => 'f'
654         }
655     );
656
657     my $label = undef;
658     my $labelexists = undef;
659     if(@$vols) {
660       # we've found an exising volume
661         if($override->{all} || grep { $_ eq 'VOLUME_LABEL_EXISTS' } @{$override->{events}}) {
662             $label = $vol->label;
663             $labelexists = 1;
664         } else {
665             return (
666                 undef, 
667                 OpenILS::Event->new('VOLUME_LABEL_EXISTS', payload => $vol->id)
668             );
669         }
670     }
671
672     # create a temp label so we can create the new volume, 
673     # then de-dup it with the existing volume
674     $vol->label( "__SYSTEM_TMP_$$".time) if $labelexists;
675
676     $vol->creator($editor->requestor->id);
677     $vol->create_date('now');
678     $vol->editor($editor->requestor->id);
679     $vol->edit_date('now');
680     $vol->clear_id;
681
682     $editor->create_asset_call_number($vol) or return (undef, $editor->die_event);
683
684     if($labelexists) {
685         # now restore the label and merge into the existing record
686         $vol->label($label);
687         return OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
688     }
689
690     return ($vol);
691 }
692
693 # returns the volume if it exists
694 sub volume_exists {
695     my($class, $e, $rec_id, $label, $owning_lib, $prefix, $suffix) = @_;
696     return $e->search_asset_call_number(
697         {label => $label, record => $rec_id, owning_lib => $owning_lib, deleted => 'f', prefix => $prefix, suffix => $suffix})->[0];
698 }
699
700 sub find_or_create_volume {
701     my($class, $e, $label, $record_id, $org_id, $prefix, $suffix, $label_class) = @_;
702
703     $prefix ||= '-1';
704     $suffix ||= '-1';
705
706     my $vol;
707
708     if($record_id == OILS_PRECAT_RECORD) {
709         $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
710             or return (undef, $e->die_event);
711
712     } else {
713         $vol = $class->volume_exists($e, $record_id, $label, $org_id, $prefix, $suffix);
714     }
715
716     # If the volume exists, return the ID
717     return ($vol, undef, 1) if $vol;
718
719     # -----------------------------------------------------------------
720     # Otherwise, create a new volume with the given attributes
721     # -----------------------------------------------------------------
722     return (undef, $e->die_event) unless $e->allowed('CREATE_VOLUME', $org_id);
723
724     $vol = Fieldmapper::asset::call_number->new;
725     $vol->owning_lib($org_id);
726     $vol->label_class($label_class) if ($label_class);
727     $vol->label($label);
728     $vol->prefix($prefix);
729     $vol->suffix($suffix);
730     $vol->record($record_id);
731
732     return $class->create_volume(0, $e, $vol);
733 }
734
735
736 sub create_copy_note {
737     my($class, $e, $copy, $title, $value, $pub) = @_;
738     my $note = Fieldmapper::asset::copy_note->new;
739     $note->owning_copy($copy->id);
740     $note->creator($e->requestor->id);
741     $note->pub($pub ? 't' : 'f');
742     $note->value($value);
743     $note->title($title);
744     $e->create_asset_copy_note($note) or return $e->die_event;
745     return undef;
746 }
747
748
749 sub remove_empty_objects {
750     my($class, $editor, $override, $vol, $force_delete_empty_bib) = @_; 
751
752     $override = { all => 1 } if($override && !ref $override);
753     $override = { all => 0 } if(!ref $override);
754
755     my $koe = $U->ou_ancestor_setting_value(
756         $editor->requestor->ws_ou, 'cat.bib.keep_on_empty', $editor);
757     my $aoe =  $U->ou_ancestor_setting_value(
758         $editor->requestor->ws_ou, 'cat.bib.alert_on_empty', $editor);
759
760     if( OpenILS::Application::Cat::BibCommon->title_is_empty($editor, $vol->record, $vol->id) ) {
761
762         # delete this volume if it's not already marked as deleted
763         unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
764             my $evt = $class->delete_volume($editor, $vol, $override, 0, 1);
765             return $evt if $evt;
766         }
767
768         return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record ) 
769             if $aoe and not ($override->{all} || grep { $_ eq 'TITLE_LAST_COPY' } @{$override->{events}}) and not $force_delete_empty_bib;
770
771         # check for any holds on the title and alert the user before plowing ahead
772         if( OpenILS::Application::Cat::BibCommon->title_has_holds($editor, $vol->record) ) {
773             return OpenILS::Event->new('TITLE_HAS_HOLDS', payload => $vol->record )
774                 if not ($override->{all} || grep { $_ eq 'TITLE_HAS_HOLDS' } @{$override->{events}}) and not $force_delete_empty_bib;
775         }
776
777         unless($koe and not $force_delete_empty_bib) {
778             # delete the bib record if the keep-on-empty setting is not set (and we're not otherwise forcing things, say through acq settings)
779             my $evt = OpenILS::Application::Cat::BibCommon->delete_rec($editor, $vol->record);
780             return $evt if $evt;
781         }
782
783     } else {
784
785         # this may be the last copy attached to the volume.  
786
787         if($U->ou_ancestor_setting_value(
788                 $editor->requestor->ws_ou, 'cat.volume.delete_on_empty', $editor)) {
789
790             # if this volume is "empty" and not mid-delete, delete it.
791             unless($U->is_true($vol->deleted) || $vol->isdeleted) {
792
793                 my $copies = $editor->search_asset_copy(
794                     [{call_number => $vol->id, deleted => 'f'}, {limit => 1}], {idlist => 1});
795
796                 if(!@$copies) {
797                     my $evt = $class->delete_volume($editor, $vol, $override, 0, 1);
798                     return $evt if $evt;
799                 }
800             }
801         }
802     }
803
804     return undef;
805 }
806
807 # Deletes a volume.  Returns undef on success, event on error
808 # force : deletes all attached copies
809 # skip_copy_check : assumes caller has verified no copies need deleting first
810 sub delete_volume {
811     my($class, $editor, $vol, $override, $delete_copies, $skip_copy_checks) = @_;
812     my $evt;
813
814     unless($skip_copy_checks) {
815         my $cs = $editor->search_asset_copy(
816             [{call_number => $vol->id, deleted => 'f'}, {limit => 1}], {idlist => 1});
817
818         return OpenILS::Event->new('VOLUME_NOT_EMPTY', payload => $vol->id) 
819             if @$cs and !$delete_copies;
820
821         my $copies = $editor->search_asset_copy({call_number => $vol->id, deleted => 'f'});
822
823         for my $copy (@$copies) {
824             $evt = $class->delete_copy($editor, $override, $vol, $copy, 0, 0, 1);
825             return $evt if $evt;
826         }
827     }
828
829     $vol->deleted('t');
830     $vol->edit_date('now');
831     $vol->editor($editor->requestor->id);
832     $editor->update_asset_call_number($vol) or return $editor->die_event;
833
834     $evt = $class->cancel_volume_holds($editor, $vol);
835     return $evt if $evt;
836
837     # handle the case where this is the last volume on the record
838     return $class->remove_empty_objects($editor, $override, $vol);
839 }
840
841
842 sub copy_perm_org {
843     my($class, $vol, $copy) = @_;
844     my $org = $vol->owning_lib;
845     if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
846         $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
847     }
848     $logger->debug("using copy perm org $org");
849     return $org;
850 }
851
852
853 sub set_item_lost {
854     my ($class, $e, $copy_id) = @_;
855
856     return $class->set_item_lost_or_lod(
857         $e, $copy_id,
858         perm => 'SET_CIRC_LOST',
859         status => OILS_COPY_STATUS_LOST,
860         alt_status => 16, #Long Overdue,
861         ous_proc_fee => OILS_SETTING_LOST_PROCESSING_FEE,
862         ous_void_od => OILS_SETTING_VOID_OVERDUE_ON_LOST,
863         bill_type => 3,
864         bill_fee_type => 4,
865         bill_note => 'Lost Materials',
866         bill_fee_note => 'Lost Materials Processing Fee',
867         event => 'COPY_MARKED_LOST',
868         stop_fines => OILS_STOP_FINES_LOST,
869         at_hook => 'lost'
870     );
871 }
872
873 sub set_item_long_overdue {
874     my ($class, $e, $copy_id) = @_;
875
876     return $class->set_item_lost_or_lod(
877         $e, $copy_id,
878         perm => 'SET_CIRC_LONG_OVERDUE',
879         status => 16, # Long Overdue
880         alt_status => OILS_COPY_STATUS_LOST,
881         ous_proc_fee => 'circ.longoverdue_materials_processing_fee',
882         ous_void_od => 'circ.void_overdue_on_longoverdue',
883         bill_type => 10,
884         bill_fee_type => 11,
885         bill_note => 'Long Overdue Materials',
886         bill_fee_note => 'Long Overdue Materials Processing Fee',
887         event => 'COPY_MARKED_LONG_OVERDUE',
888         stop_fines => 'LONGOVERDUE',
889         at_hook => 'longoverdue'
890     );
891 }
892
893 # LOST or LONGOVERDUE
894 # basic process is the same.  details change.
895 sub set_item_lost_or_lod {
896     my ($class, $e, $copy_id, %args) = @_;
897
898     my $copy = $e->retrieve_asset_copy([
899         $copy_id, 
900         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
901             or return $e->die_event;
902
903     my $owning_lib = 
904         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
905             $copy->circ_lib : $copy->call_number->owning_lib;
906
907     my $circ = $e->search_action_circulation(
908         {checkin_time => undef, target_copy => $copy->id} )->[0]
909             or return $e->die_event;
910
911     $e->allowed($args{perm}, $circ->circ_lib) or return $e->die_event;
912
913     return $e->die_event(OpenILS::Event->new($args{event}))
914             if ($copy->status == $args{status} || $copy->status == $args{alt_status});
915
916     # ---------------------------------------------------------------------
917     # fetch the related org settings
918     my $proc_fee = $U->ou_ancestor_setting_value(
919         $owning_lib, $args{ous_proc_fee}, $e) || 0;
920     my $void_overdue = $U->ou_ancestor_setting_value(
921         $owning_lib, $args{ous_void_od}, $e) || 0;
922
923     # ---------------------------------------------------------------------
924     # move the copy into LOST status
925     $copy->status($args{status});
926     $copy->editor($e->requestor->id);
927     $copy->edit_date('now');
928     $e->update_asset_copy($copy) or return $e->die_event;
929
930     my $price = $U->get_copy_price($e, $copy, $copy->call_number);
931
932     if( $price > 0 ) {
933         my $evt = OpenILS::Application::Circ::CircCommon->create_bill($e, 
934             $price, $args{bill_type}, $args{bill_note}, $circ->id);
935         return $evt if $evt;
936     }
937
938     # ---------------------------------------------------------------------
939     # if there is a processing fee, charge that too
940     if( $proc_fee > 0 ) {
941         my $evt = OpenILS::Application::Circ::CircCommon->create_bill($e, 
942             $proc_fee, $args{bill_fee_type}, $args{bill_fee_note}, $circ->id);
943         return $evt if $evt;
944     }
945
946     # ---------------------------------------------------------------------
947     # mark the circ as lost and stop the fines
948     $circ->stop_fines($args{stop_fines});
949     $circ->stop_fines_time('now') unless $circ->stop_fines_time;
950     $e->update_action_circulation($circ) or return $e->die_event;
951
952     # ---------------------------------------------------------------------
953     # zero out overdue fines on this circ if configured
954     if( $void_overdue ) {
955         my $evt = OpenILS::Application::Circ::CircCommon->void_or_zero_overdues($e, $circ, {force_zero => 1, note => "System: OVERDUE REVERSED for " . $args{bill_note} . " Processing"});
956         return $evt if $evt;
957     }
958
959     my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
960     return $evt if $evt;
961
962     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
963     $ses->request(
964         'open-ils.trigger.event.autocreate', 
965         $args{at_hook}, $circ, $circ->circ_lib
966     );
967
968     my $evt2 = OpenILS::Utils::Penalty->calculate_penalties(
969         $e, $circ->usr, $U->xact_org($circ->id, $e));
970     return $evt2 if $evt2;
971
972     return undef;
973 }