]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Cat/AssetCommon.pm
Delete volume on last copy setting
[working/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::Application::Circ::CircCommon;
13 my $U = 'OpenILS::Application::AppUtils';
14
15
16 # ---------------------------------------------------------------------------
17 # Shared copy mangling code.  Do not publish methods from here.
18 # ---------------------------------------------------------------------------
19
20 sub org_cannot_have_vols {
21     my($class, $e, $org_id) = @_;
22         my $org = $e->retrieve_actor_org_unit([
23         $org_id,
24         {   flesh => 1,
25             flesh_fields => {aou => ['ou_type']}
26         }]) or return $e->event;
27
28         return OpenILS::Event->new('ORG_CANNOT_HAVE_VOLS')
29                 unless $U->is_true($org->ou_type->can_have_vols);
30
31         return 0;
32 }
33
34 sub fix_copy_price {
35     my $class = shift;
36         my $copy = shift;
37
38     if(defined $copy->price) {
39             my $p = $copy->price || 0;
40             $p =~ s/\$//og;
41             $copy->price($p);
42     }
43
44         my $d = $copy->deposit_amount || 0;
45         $d =~ s/\$//og;
46         $copy->deposit_amount($d);
47 }
48
49 sub create_copy {
50         my($class, $editor, $vol, $copy) = @_;
51
52         my $existing = $editor->search_asset_copy(
53                 { barcode => $copy->barcode, deleted => 'f' } );
54         
55         return OpenILS::Event->new('ITEM_BARCODE_EXISTS') if @$existing;
56
57    # see if the volume this copy references is marked as deleted
58     return OpenILS::Event->new('VOLUME_DELETED', vol => $vol->id) 
59         if $U->is_true($vol->deleted);
60
61         my $evt;
62         my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
63         return $evt if ($evt = $class->org_cannot_have_vols($editor, $org));
64
65         $copy->clear_id;
66         $copy->editor($editor->requestor->id);
67         $copy->creator($editor->requestor->id);
68         $copy->create_date('now');
69     $copy->call_number($vol->id);
70         $class->fix_copy_price($copy);
71
72         $editor->create_asset_copy($copy) or return $editor->die_event;
73         return undef;
74 }
75
76
77 # if 'delete_stats' is true, the copy->stat_cat_entries data is 
78 # treated as the authoritative list for the copy. existing entries
79 # that are not in said list will be deleted from the DB
80 sub update_copy_stat_entries {
81         my($class, $editor, $copy, $delete_stats) = @_;
82
83         return undef if $copy->isdeleted;
84         return undef unless $copy->ischanged or $copy->isnew;
85
86         my $evt;
87         my $entries = $copy->stat_cat_entries;
88
89         if( $delete_stats ) {
90                 $entries = ($entries and @$entries) ? $entries : [];
91         } else {
92                 return undef unless ($entries and @$entries);
93         }
94
95         my $maps = $editor->search_asset_stat_cat_entry_copy_map({owning_copy=>$copy->id});
96
97         if(!$copy->isnew) {
98                 # if there is no stat cat entry on the copy who's id matches the
99                 # current map's id, remove the map from the database
100                 for my $map (@$maps) {
101                         if(! grep { $_->id == $map->stat_cat_entry } @$entries ) {
102
103                                 $logger->info("copy update found stale ".
104                                         "stat cat entry map ".$map->id. " on copy ".$copy->id);
105
106                                 $editor->delete_asset_stat_cat_entry_copy_map($map)
107                                         or return $editor->event;
108                         }
109                 }
110         }
111
112         # go through the stat cat update/create process
113         for my $entry (@$entries) { 
114                 next unless $entry;
115
116                 # if this link already exists in the DB, don't attempt to re-create it
117                 next if( grep{$_->stat_cat_entry == $entry->id} @$maps );
118         
119                 my $new_map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
120
121                 my $sc = ref($entry->stat_cat) ? $entry->stat_cat->id : $entry->stat_cat;
122                 
123                 $new_map->stat_cat( $sc );
124                 $new_map->stat_cat_entry( $entry->id );
125                 $new_map->owning_copy( $copy->id );
126
127                 $editor->create_asset_stat_cat_entry_copy_map($new_map)
128                         or return $editor->event;
129
130                 $logger->info("copy update created new stat cat entry map ".$editor->data);
131         }
132
133         return undef;
134 }
135
136 # if 'delete_maps' is true, the copy->parts data is  treated as the
137 # authoritative list for the copy. existing part maps not targeting
138 # these parts will be deleted from the DB
139 sub update_copy_parts {
140         my($class, $editor, $copy, $delete_maps) = @_;
141
142         return undef if $copy->isdeleted;
143         return undef unless $copy->ischanged or $copy->isnew;
144
145         my $evt;
146         my $incoming_parts = $copy->parts;
147
148         if( $delete_maps ) {
149                 $incoming_parts = ($incoming_parts and @$incoming_parts) ? $incoming_parts : [];
150         } else {
151                 return undef unless ($incoming_parts and @$incoming_parts);
152         }
153
154         my $maps = $editor->search_asset_copy_part_map({target_copy=>$copy->id});
155
156         if(!$copy->isnew) {
157                 # if there is no part map on the copy who's id matches the
158                 # current map's id, remove the map from the database
159                 for my $map (@$maps) {
160                         if(! grep { $_->id == $map->part } @$incoming_parts ) {
161
162                                 $logger->info("copy update found stale ".
163                                         "monographic part map ".$map->id. " on copy ".$copy->id);
164
165                                 $editor->delete_asset_copy_part_map($map)
166                                         or return $editor->event;
167                         }
168                 }
169         }
170
171         # go through the part map update/create process
172         for my $incoming_part (@$incoming_parts) { 
173                 next unless $incoming_part;
174
175                 # if this link already exists in the DB, don't attempt to re-create it
176                 next if( grep{$_->part == $incoming_part->id} @$maps );
177         
178                 my $new_map = Fieldmapper::asset::copy_part_map->new();
179
180                 $new_map->part( $incoming_part->id );
181                 $new_map->target_copy( $copy->id );
182
183                 $editor->create_asset_copy_part_map($new_map)
184                         or return $editor->event;
185
186                 $logger->info("copy update created new monographic part copy map ".$editor->data);
187         }
188
189         return undef;
190 }
191
192
193
194 sub update_copy {
195         my($class, $editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib) = @_;
196
197         my $evt;
198         my $org = (ref $copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
199         return $evt if ( $evt = $class->org_cannot_have_vols($editor, $org) );
200
201         $logger->info("vol-update: updating copy ".$copy->id);
202         my $orig_copy = $editor->retrieve_asset_copy($copy->id);
203
204     # Call-number may have changed, find the original
205     my $orig_vol_id = $editor->json_query({select => {acp => ['call_number']}, from => 'acp', where => {id => $copy->id}});
206     my $orig_vol  = $editor->retrieve_asset_call_number($orig_vol_id->[0]->{call_number});
207
208         $copy->editor($editor->requestor->id);
209         $copy->edit_date('now');
210
211         $copy->age_protect( $copy->age_protect->id )
212                 if ref $copy->age_protect;
213
214         $class->fix_copy_price($copy);
215     $class->check_hold_retarget($editor, $copy, $orig_copy, $retarget_holds);
216
217         return $editor->event unless $editor->update_asset_copy($copy);
218         return $class->remove_empty_objects($editor, $override, $orig_vol, $force_delete_empty_bib);
219 }
220
221 sub check_hold_retarget {
222     my($class, $editor, $copy, $orig_copy, $retarget_holds) = @_;
223     return unless $retarget_holds;
224
225     if( !($copy->isdeleted or $U->is_true($copy->deleted)) ) {
226         # see if a status change warrants a retarget
227
228         $orig_copy = $editor->retrieve_asset_copy($copy->id) unless $orig_copy;
229
230         if($orig_copy->status == $copy->status) {
231             # no status change, no retarget
232             return;
233         }
234
235         my $stat = $editor->retrieve_config_copy_status($copy->status);
236
237         # new status is holdable, no retarget. Later add logic to find potential 
238         # holds and retarget those to pick up the newly available copy
239         return if $U->is_true($stat->holdable); 
240     }
241
242     my $hold_ids = $editor->search_action_hold_request(
243         {   current_copy        => $copy->id, 
244             cancel_time         => undef, 
245             fulfillment_time    => undef 
246         }, {idlist => 1}
247     );
248
249     push(@$retarget_holds, @$hold_ids);
250 }
251
252
253 # this does the actual work
254 sub update_fleshed_copies {
255         my($class, $editor, $override, $vol, $copies, $delete_stats, $retarget_holds, $force_delete_empty_bib) = @_;
256
257         my $evt;
258         my $fetchvol = ($vol) ? 0 : 1;
259
260         my %cache;
261         $cache{$vol->id} = $vol if $vol;
262
263         for my $copy (@$copies) {
264
265                 my $copyid = $copy->id;
266                 $logger->info("vol-update: inspecting copy $copyid");
267
268                 if( !($vol = $cache{$copy->call_number}) ) {
269                         $vol = $cache{$copy->call_number} = 
270                                 $editor->retrieve_asset_call_number($copy->call_number);
271                         return $editor->event unless $vol;
272                 }
273
274                 return $editor->event unless 
275                         $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
276
277                 $copy->editor($editor->requestor->id);
278                 $copy->edit_date('now');
279
280                 $copy->status( $copy->status->id ) if ref($copy->status);
281                 $copy->location( $copy->location->id ) if ref($copy->location);
282                 $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
283                 
284                 my $sc_entries = $copy->stat_cat_entries;
285                 $copy->clear_stat_cat_entries;
286
287         my $parts = $copy->parts;
288                 $copy->clear_parts;
289
290                 if( $copy->isdeleted ) {
291                         $evt = $class->delete_copy($editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib);
292                         return $evt if $evt;
293
294                 } elsif( $copy->isnew ) {
295                         $evt = $class->create_copy( $editor, $vol, $copy );
296                         return $evt if $evt;
297
298                 } elsif( $copy->ischanged ) {
299
300                         $evt = $class->update_copy( $editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib);
301                         return $evt if $evt;
302                 }
303
304                 $copy->stat_cat_entries( $sc_entries );
305                 $evt = $class->update_copy_stat_entries($editor, $copy, $delete_stats);
306                 $copy->parts( $parts );
307                 # probably okay to use $delete_stats here for simplicity
308                 $evt = $class->update_copy_parts($editor, $copy, $delete_stats);
309                 return $evt if $evt;
310         }
311
312         $logger->debug("vol-update: done updating copy batch");
313
314         return undef;
315 }
316
317
318 sub delete_copy {
319         my($class, $editor, $override, $vol, $copy, $retarget_holds, $force_delete_empty_bib, $skip_empty_cleanup) = @_;
320
321    return $editor->event unless 
322       $editor->allowed('DELETE_COPY', $class->copy_perm_org($vol, $copy));
323
324         my $stat = $U->copy_status($copy->status)->id;
325
326         unless($override) {
327                 return OpenILS::Event->new('COPY_DELETE_WARNING', payload => $copy->id )
328                         if $stat == OILS_COPY_STATUS_CHECKED_OUT or
329                                 $stat == OILS_COPY_STATUS_IN_TRANSIT or
330                                 $stat == OILS_COPY_STATUS_ON_HOLDS_SHELF or
331                                 $stat == OILS_COPY_STATUS_ILL;
332         }
333
334         $logger->info("vol-update: deleting copy ".$copy->id);
335         $copy->deleted('t');
336
337         $copy->editor($editor->requestor->id);
338         $copy->edit_date('now');
339         $editor->update_asset_copy($copy) or return $editor->event;
340
341         # Delete any open transits for this copy
342         my $transits = $editor->search_action_transit_copy(
343                 { target_copy=>$copy->id, dest_recv_time => undef } );
344
345         for my $t (@$transits) {
346                 $editor->delete_action_transit_copy($t)
347                         or return $editor->event;
348         }
349
350     $class->check_hold_retarget($editor, $copy, undef, $retarget_holds);
351
352     return undef if $skip_empty_cleanup;
353
354         return $class->remove_empty_objects($editor, $override, $vol, $force_delete_empty_bib);
355 }
356
357
358
359 sub create_volume {
360         my($class, $override, $editor, $vol) = @_;
361         my $evt;
362
363         return $evt if ( $evt = $class->org_cannot_have_vols($editor, $vol->owning_lib) );
364
365    # see if the record this volume references is marked as deleted
366    my $rec = $editor->retrieve_biblio_record_entry($vol->record)
367       or return $editor->die_event;
368    return OpenILS::Event->new('BIB_RECORD_DELETED', rec => $rec->id) 
369       if $U->is_true($rec->deleted);
370
371         # first lets see if there are any collisions
372         my $vols = $editor->search_asset_call_number( { 
373                         owning_lib      => $vol->owning_lib,
374                         record          => $vol->record,
375                         label                   => $vol->label,
376                         prefix                  => $vol->prefix,
377                         suffix                  => $vol->suffix,
378                         deleted         => 'f'
379                 }
380         );
381
382         my $label = undef;
383         if(@$vols) {
384       # we've found an exising volume
385                 if($override) { 
386                         $label = $vol->label;
387                 } else {
388                         return OpenILS::Event->new(
389                                 'VOLUME_LABEL_EXISTS', payload => $vol->id);
390                 }
391         }
392
393         # create a temp label so we can create the new volume, 
394     # then de-dup it with the existing volume
395         $vol->label( "__SYSTEM_TMP_$$".time) if $label;
396
397         $vol->creator($editor->requestor->id);
398         $vol->create_date('now');
399         $vol->editor($editor->requestor->id);
400         $vol->edit_date('now');
401         $vol->clear_id;
402
403         $editor->create_asset_call_number($vol) or return $editor->die_event;
404
405         if($label) {
406                 # now restore the label and merge into the existing record
407                 $vol->label($label);
408                 (undef, $evt) = 
409                         OpenILS::Application::Cat::Merge::merge_volumes($editor, [$vol], $$vols[0]);
410                 return $evt if $evt;
411         }
412
413         return undef;
414 }
415
416 # returns the volume if it exists
417 sub volume_exists {
418     my($class, $e, $rec_id, $label, $owning_lib, $prefix, $suffix) = @_;
419     return $e->search_asset_call_number(
420         {label => $label, record => $rec_id, owning_lib => $owning_lib, deleted => 'f', prefix => $prefix, suffix => $suffix})->[0];
421 }
422
423 sub find_or_create_volume {
424         my($class, $e, $label, $record_id, $org_id, $prefix, $suffix, $label_class) = @_;
425
426     $prefix ||= '-1';
427     $suffix ||= '-1';
428
429     my $vol;
430
431     if($record_id == OILS_PRECAT_RECORD) {
432         $vol = $e->retrieve_asset_call_number(OILS_PRECAT_CALL_NUMBER)
433             or return (undef, $e->die_event);
434
435     } else {
436         $vol = $class->volume_exists($e, $record_id, $label, $org_id, $prefix, $suffix);
437     }
438
439         # If the volume exists, return the ID
440     return ($vol, undef, 1) if $vol;
441
442         # -----------------------------------------------------------------
443         # Otherwise, create a new volume with the given attributes
444         # -----------------------------------------------------------------
445         return (undef, $e->die_event) unless $e->allowed('UPDATE_VOLUME', $org_id);
446
447         $vol = Fieldmapper::asset::call_number->new;
448         $vol->owning_lib($org_id);
449         $vol->label_class($label_class) if ($label_class);
450         $vol->label($label);
451         $vol->prefix($prefix);
452         $vol->suffix($suffix);
453         $vol->record($record_id);
454
455     my $evt = $class->create_volume(0, $e, $vol);
456     return (undef, $evt) if $evt;
457
458         return ($vol);
459 }
460
461
462 sub create_copy_note {
463     my($class, $e, $copy, $title, $value, $pub) = @_;
464     my $note = Fieldmapper::asset::copy_note->new;
465     $note->owning_copy($copy->id);
466     $note->creator($e->requestor->id);
467     $note->pub('t');
468     $note->value($value);
469     $note->title($title);
470     $e->create_asset_copy_note($note) or return $e->die_event;
471     return undef;
472 }
473
474
475 sub remove_empty_objects {
476         my($class, $editor, $override, $vol, $force_delete_empty_bib) = @_; 
477
478     my $koe = $U->ou_ancestor_setting_value(
479         $editor->requestor->ws_ou, 'cat.bib.keep_on_empty', $editor);
480     my $aoe =  $U->ou_ancestor_setting_value(
481         $editor->requestor->ws_ou, 'cat.bib.alert_on_empty', $editor);
482
483         if( OpenILS::Application::Cat::BibCommon->title_is_empty($editor, $vol->record, $vol->id) ) {
484
485         # delete this volume if it's not already marked as deleted
486         unless( $U->is_true($vol->deleted) || $vol->isdeleted ) {
487             my $evt = $class->delete_volume($editor, $vol, $override, 0, 1);
488             return $evt if $evt;
489         }
490
491         return OpenILS::Event->new('TITLE_LAST_COPY', payload => $vol->record ) 
492             if $aoe and not $override and not $force_delete_empty_bib;
493
494         unless($koe and not $force_delete_empty_bib) {
495             # delete the bib record if the keep-on-empty setting is not set (and we're not otherwise forcing things, say through acq settings)
496             my $evt = OpenILS::Application::Cat::BibCommon->delete_rec($editor, $vol->record);
497             return $evt if $evt;
498         }
499
500         } else {
501
502         # this may be the last copy attached to the volume.  
503
504         if($U->ou_ancestor_setting_value(
505                 $editor->requestor->ws_ou, 'cat.volume.delete_on_empty', $editor)) {
506
507             # if this volume is "empty" and not mid-delete, delete it.
508             unless($U->is_true($vol->deleted) || $vol->isdeleted) {
509
510                 my $copies = $editor->search_asset_copy(
511                     [{call_number => $vol->id, deleted => 'f'}, {limit => 1}], {idlist => 1});
512
513                 if(!@$copies) {
514                     my $evt = $class->delete_volume($editor, $vol, $override, 0, 1);
515                     return $evt if $evt;
516                 }
517             }
518         }
519     }
520
521         return undef;
522 }
523
524 # Deletes a volume.  Returns undef on success, event on error
525 # force : deletes all attached copies
526 # skip_copy_check : assumes caller has verified no copies need deleting first
527 sub delete_volume {
528     my($class, $editor, $vol, $override, $delete_copies, $skip_copy_checks) = @_;
529     my $evt;
530
531     unless($skip_copy_checks) {
532         my $cs = $editor->search_asset_copy(
533             [{call_number => $vol->id, deleted => 'f'}, {limit => 1}], {idlist => 1});
534
535         return OpenILS::Event->new('VOLUME_NOT_EMPTY', payload => $vol->id) 
536             if @$cs and !$delete_copies;
537
538         my $copies = $editor->search_asset_copy({call_number => $vol->id, deleted => 'f'});
539
540         for my $copy (@$copies) {
541             $evt = $class->delete_copy($editor, $override, $vol, $copy, 0, 0, 1);
542             return $evt if $evt;
543         }
544     }
545
546     $vol->deleted('t');
547     $vol->edit_date('now');
548     $vol->editor($editor->requestor->id);
549     $editor->update_asset_call_number($vol) or return $editor->die_event;
550
551     # handle the case where this is the last volume on the record
552         return $class->remove_empty_objects($editor, $override, $vol);
553 }
554
555
556 sub copy_perm_org {
557         my($class, $vol, $copy) = @_;
558         my $org = $vol->owning_lib;
559         if( $vol->id == OILS_PRECAT_CALL_NUMBER ) {
560                 $org = ref($copy->circ_lib) ? $copy->circ_lib->id : $copy->circ_lib;
561         }
562         $logger->debug("using copy perm org $org");
563         return $org;
564 }
565
566
567 sub set_item_lost {
568     my($class, $e, $copy_id) = @_;
569
570     my $copy = $e->retrieve_asset_copy([
571         $copy_id, 
572         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
573             or return $e->die_event;
574
575     my $owning_lib = 
576         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
577             $copy->circ_lib : $copy->call_number->owning_lib;
578
579     my $circ = $e->search_action_circulation(
580         {checkin_time => undef, target_copy => $copy->id} )->[0]
581             or return $e->die_event;
582
583     $e->allowed('SET_CIRC_LOST', $circ->circ_lib) or return $e->die_event;
584
585     return $e->die_event(OpenILS::Event->new('COPY_MARKED_LOST'))
586             if $copy->status == OILS_COPY_STATUS_LOST;
587
588     # ---------------------------------------------------------------------
589     # fetch the related org settings
590     my $proc_fee = $U->ou_ancestor_setting_value(
591         $owning_lib, OILS_SETTING_LOST_PROCESSING_FEE, $e) || 0;
592     my $void_overdue = $U->ou_ancestor_setting_value(
593         $owning_lib, OILS_SETTING_VOID_OVERDUE_ON_LOST, $e) || 0;
594
595     # ---------------------------------------------------------------------
596     # move the copy into LOST status
597     $copy->status(OILS_COPY_STATUS_LOST);
598     $copy->editor($e->requestor->id);
599     $copy->edit_date('now');
600     $e->update_asset_copy($copy) or return $e->die_event;
601
602     my $price = $U->get_copy_price($e, $copy, $copy->call_number);
603
604     if( $price > 0 ) {
605         my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
606             $e, $price, 3, 'Lost Materials', $circ->id);
607         return $evt if $evt;
608     }
609
610     # ---------------------------------------------------------------------
611     # if there is a processing fee, charge that too
612     if( $proc_fee > 0 ) {
613         my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
614             $e, $proc_fee, 4, 'Lost Materials Processing Fee', $circ->id);
615         return $evt if $evt;
616     }
617
618     # ---------------------------------------------------------------------
619     # mark the circ as lost and stop the fines
620     $circ->stop_fines(OILS_STOP_FINES_LOST);
621     $circ->stop_fines_time('now') unless $circ->stop_fines_time;
622     $e->update_action_circulation($circ) or return $e->die_event;
623
624     # ---------------------------------------------------------------------
625     # void all overdue fines on this circ if configured
626     if( $void_overdue ) {
627         my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ);
628         return $evt if $evt;
629     }
630
631     my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
632     return $evt if $evt;
633
634     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
635     $ses->request('open-ils.trigger.event.autocreate', 'lost', $circ, $circ->circ_lib);
636
637     return undef;
638 }