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