Bug 27883: Add ability to preserve patron field from being overwritten by import
[koha.git] / Koha / Hold.pm
1 package Koha::Hold;
2
3 # Copyright ByWater Solutions 2014
4 # Copyright 2017 Koha Development team
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 use Carp;
24 use Data::Dumper qw(Dumper);
25 use List::MoreUtils qw(any);
26
27 use C4::Context qw(preference);
28 use C4::Letters;
29 use C4::Log;
30
31 use Koha::AuthorisedValues;
32 use Koha::DateUtils qw(dt_from_string output_pref);
33 use Koha::Patrons;
34 use Koha::Biblios;
35 use Koha::Items;
36 use Koha::Libraries;
37 use Koha::Old::Holds;
38 use Koha::Calendar;
39
40 use Koha::Exceptions::Hold;
41
42 use base qw(Koha::Object);
43
44 =head1 NAME
45
46 Koha::Hold - Koha Hold object class
47
48 =head1 API
49
50 =head2 Class methods
51
52 =cut
53
54 =head3 age
55
56 returns the number of days since a hold was placed, optionally
57 using the calendar
58
59 my $age = $hold->age( $use_calendar );
60
61 =cut
62
63 sub age {
64     my ( $self, $use_calendar ) = @_;
65
66     my $today = dt_from_string;
67     my $age;
68
69     if ( $use_calendar ) {
70         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
71         $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
72     }
73     else {
74         $age = $today->delta_days( dt_from_string( $self->reservedate ) );
75     }
76
77     $age = $age->in_units( 'days' );
78
79     return $age;
80 }
81
82 =head3 suspend_hold
83
84 my $hold = $hold->suspend_hold( $suspend_until_dt );
85
86 =cut
87
88 sub suspend_hold {
89     my ( $self, $dt ) = @_;
90
91     my $date = $dt ? $dt->clone()->truncate( to => 'day' )->datetime : undef;
92
93     if ( $self->is_found ) {    # We can't suspend found holds
94         if ( $self->is_waiting ) {
95             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
96         }
97         elsif ( $self->is_in_transit ) {
98             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
99         }
100         elsif ( $self->is_in_processing ) {
101             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
102         }
103         else {
104             Koha::Exceptions::Hold::CannotSuspendFound->throw(
105                       'Unhandled data exception on found hold (id='
106                     . $self->id
107                     . ', found='
108                     . $self->found
109                     . ')' );
110         }
111     }
112
113     $self->suspend(1);
114     $self->suspend_until($date);
115     $self->store();
116
117     logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, Dumper( $self->unblessed ) )
118         if C4::Context->preference('HoldsLog');
119
120     return $self;
121 }
122
123 =head3 resume
124
125 my $hold = $hold->resume();
126
127 =cut
128
129 sub resume {
130     my ( $self ) = @_;
131
132     $self->suspend(0);
133     $self->suspend_until( undef );
134
135     $self->store();
136
137     logaction( 'HOLDS', 'RESUME', $self->reserve_id, Dumper($self->unblessed) )
138         if C4::Context->preference('HoldsLog');
139
140     return $self;
141 }
142
143 =head3 delete
144
145 $hold->delete();
146
147 =cut
148
149 sub delete {
150     my ( $self ) = @_;
151
152     my $deleted = $self->SUPER::delete($self);
153
154     logaction( 'HOLDS', 'DELETE', $self->reserve_id, Dumper($self->unblessed) )
155         if C4::Context->preference('HoldsLog');
156
157     return $deleted;
158 }
159
160 =head3 set_transfer
161
162 =cut
163
164 sub set_transfer {
165     my ( $self ) = @_;
166
167     $self->priority(0);
168     $self->found('T');
169     $self->store();
170
171     return $self;
172 }
173
174 =head3 set_waiting
175
176 =cut
177
178 sub set_waiting {
179     my ( $self, $desk_id ) = @_;
180
181     $self->priority(0);
182
183     my $today = dt_from_string();
184     my $values = {
185         found => 'W',
186         waitingdate => $today->ymd,
187         desk_id => $desk_id,
188     };
189
190     my $requested_expiration;
191     if ($self->expirationdate) {
192         $requested_expiration = dt_from_string($self->expirationdate);
193     }
194
195     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
196     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
197
198     my $expirationdate = $today->clone;
199     $expirationdate->add(days => $max_pickup_delay);
200
201     if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
202         my $itemtype = $self->item ? $self->item->effective_itemtype : $self->biblio->itemtype;
203         my $daysmode = Koha::CirculationRules->get_effective_daysmode(
204             {
205                 categorycode => $self->borrower->categorycode,
206                 itemtype     => $itemtype,
207                 branchcode   => $self->branchcode,
208             }
209         );
210         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode, days_mode => $daysmode );
211
212         $expirationdate = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
213     }
214
215     # If patron's requested expiration date is prior to the
216     # calculated one, we keep the patron's one.
217     my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
218     $values->{expirationdate} = $cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd;
219
220     $self->set($values)->store();
221
222     return $self;
223 }
224
225 =head3 is_pickup_location_valid
226
227     if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
228         ...
229     }
230
231 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
232 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
233 passed.
234
235 =cut
236
237 sub is_pickup_location_valid {
238     my ( $self, $params ) = @_;
239
240     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
241         unless $params->{library_id};
242
243     my @pickup_locations;
244
245     if ( $self->itemnumber ) { # item-level
246         @pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
247     }
248     else { # biblio-level
249         @pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
250     }
251
252     return any { $_->branchcode eq $params->{library_id} } @pickup_locations;
253 }
254
255 =head3 set_pickup_location
256
257     $hold->set_pickup_location(
258         {
259             library_id => $library->id,
260           [ force   => 0|1 ]
261         }
262     );
263
264 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
265 the passed pickup location is not valid.
266
267 Note: It is up to the caller to verify if I<AllowHoldPolicyOverride> is set when setting the
268 B<force> parameter.
269
270 =cut
271
272 sub set_pickup_location {
273     my ( $self, $params ) = @_;
274
275     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
276         unless $params->{library_id};
277
278     if (
279         $params->{force}
280         || $self->is_pickup_location_valid(
281             { library_id => $params->{library_id} }
282         )
283       )
284     {
285         # all good, set the new pickup location
286         $self->branchcode( $params->{library_id} )->store;
287     }
288     else {
289         Koha::Exceptions::Hold::InvalidPickupLocation->throw;
290     }
291
292     return $self;
293 }
294
295 =head3 set_processing
296
297 $hold->set_processing;
298
299 Mark the hold as in processing.
300
301 =cut
302
303 sub set_processing {
304     my ( $self ) = @_;
305
306     $self->priority(0);
307     $self->found('P');
308     $self->store();
309
310     return $self;
311 }
312
313 =head3 is_found
314
315 Returns true if hold is waiting, in transit or in processing
316
317 =cut
318
319 sub is_found {
320     my ($self) = @_;
321
322     return 0 unless $self->found();
323     return 1 if $self->found() eq 'W';
324     return 1 if $self->found() eq 'T';
325     return 1 if $self->found() eq 'P';
326 }
327
328 =head3 is_waiting
329
330 Returns true if hold is a waiting hold
331
332 =cut
333
334 sub is_waiting {
335     my ($self) = @_;
336
337     my $found = $self->found;
338     return $found && $found eq 'W';
339 }
340
341 =head3 is_in_transit
342
343 Returns true if hold is a in_transit hold
344
345 =cut
346
347 sub is_in_transit {
348     my ($self) = @_;
349
350     return 0 unless $self->found();
351     return $self->found() eq 'T';
352 }
353
354 =head3 is_in_processing
355
356 Returns true if hold is a in_processing hold
357
358 =cut
359
360 sub is_in_processing {
361     my ($self) = @_;
362
363     return 0 unless $self->found();
364     return $self->found() eq 'P';
365 }
366
367 =head3 is_cancelable_from_opac
368
369 Returns true if hold is a cancelable hold
370
371 Holds may be only canceled if they are not found.
372
373 This is used from the OPAC.
374
375 =cut
376
377 sub is_cancelable_from_opac {
378     my ($self) = @_;
379
380     return 1 unless $self->is_found();
381     return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
382 }
383
384 =head3 is_at_destination
385
386 Returns true if hold is waiting
387 and the hold's pickup branch matches
388 the hold item's holding branch
389
390 =cut
391
392 sub is_at_destination {
393     my ($self) = @_;
394
395     return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
396 }
397
398 =head3 biblio
399
400 Returns the related Koha::Biblio object for this hold
401
402 =cut
403
404 sub biblio {
405     my ($self) = @_;
406
407     $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
408
409     return $self->{_biblio};
410 }
411
412 =head3 patron
413
414 Returns the related Koha::Patron object for this hold
415
416 =cut
417
418 sub patron {
419     my ($self) = @_;
420
421     my $patron_rs = $self->_result->patron;
422     return Koha::Patron->_new_from_dbic($patron_rs);
423 }
424
425 =head3 item
426
427 Returns the related Koha::Item object for this Hold
428
429 =cut
430
431 sub item {
432     my ($self) = @_;
433
434     $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
435
436     return $self->{_item};
437 }
438
439 =head3 branch
440
441 Returns the related Koha::Library object for this Hold
442
443 =cut
444
445 sub branch {
446     my ($self) = @_;
447
448     $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
449
450     return $self->{_branch};
451 }
452
453 =head3 desk
454
455 Returns the related Koha::Desk object for this Hold
456
457 =cut
458
459 sub desk {
460     my $self = shift;
461     my $desk_rs = $self->_result->desk;
462     return unless $desk_rs;
463     return Koha::Desk->_new_from_dbic($desk_rs);
464 }
465
466 =head3 borrower
467
468 Returns the related Koha::Patron object for this Hold
469
470 =cut
471
472 # FIXME Should be renamed with ->patron
473 sub borrower {
474     my ($self) = @_;
475
476     $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
477
478     return $self->{_borrower};
479 }
480
481 =head3 is_suspended
482
483 my $bool = $hold->is_suspended();
484
485 =cut
486
487 sub is_suspended {
488     my ( $self ) = @_;
489
490     return $self->suspend();
491 }
492
493
494 =head3 cancel
495
496 my $cancel_hold = $hold->cancel(
497     {
498         [ charge_cancel_fee => 1||0, ]
499         [ cancellation_reason => $cancellation_reason, ]
500     }
501 );
502
503 Cancel a hold:
504 - The hold will be moved to the old_reserves table with a priority=0
505 - The priority of other holds will be updated
506 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
507 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
508 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
509
510 =cut
511
512 sub cancel {
513     my ( $self, $params ) = @_;
514     $self->_result->result_source->schema->txn_do(
515         sub {
516             $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
517             $self->priority(0);
518             $self->cancellation_reason( $params->{cancellation_reason} );
519             $self->store();
520
521             if ( $params->{cancellation_reason} ) {
522                 my $letter = C4::Letters::GetPreparedLetter(
523                     module                 => 'reserves',
524                     letter_code            => 'HOLD_CANCELLATION',
525                     message_transport_type => 'email',
526                     branchcode             => $self->borrower->branchcode,
527                     lang                   => $self->borrower->lang,
528                     tables => {
529                         branches    => $self->borrower->branchcode,
530                         borrowers   => $self->borrowernumber,
531                         items       => $self->itemnumber,
532                         biblio      => $self->biblionumber,
533                         biblioitems => $self->biblionumber,
534                         reserves    => $self->unblessed,
535                     }
536                 );
537
538                 if ($letter) {
539                     C4::Letters::EnqueueLetter(
540                         {
541                             letter                   => $letter,
542                             borrowernumber         => $self->borrowernumber,
543                             message_transport_type => 'email',
544                         }
545                     );
546                 }
547             }
548
549             $self->_move_to_old;
550             $self->SUPER::delete(); # Do not add a DELETE log
551
552             # now fix the priority on the others....
553             C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
554
555             # and, if desired, charge a cancel fee
556             my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
557             if ( $charge && $params->{'charge_cancel_fee'} ) {
558                 my $account =
559                   Koha::Account->new( { patron_id => $self->borrowernumber } );
560                 $account->add_debit(
561                     {
562                         amount     => $charge,
563                         user_id    => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
564                         interface  => C4::Context->interface,
565                         library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
566                         type       => 'RESERVE_EXPIRED',
567                         item_id    => $self->itemnumber
568                     }
569                 );
570             }
571
572             C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, Dumper($self->unblessed) )
573                 if C4::Context->preference('HoldsLog');
574         }
575     );
576     return $self;
577 }
578
579 =head3 store
580
581 Override base store method to set default
582 expirationdate for holds.
583
584 =cut
585
586 sub store {
587     my ($self) = @_;
588
589     if ( !$self->in_storage ) {
590         if (
591             C4::Context->preference('DefaultHoldExpirationdate')
592             and ( not defined $self->expirationdate
593                 or $self->expirationdate eq '' )
594           )
595         {
596             $self->_set_default_expirationdate;
597         }
598     }
599     else {
600
601         my %updated_columns = $self->_result->get_dirty_columns;
602         return $self->SUPER::store unless %updated_columns;
603
604         if ( exists $updated_columns{reservedate} ) {
605             if (
606                 C4::Context->preference('DefaultHoldExpirationdate')
607                 and ( not exists $updated_columns{expirationdate}
608                     or exists $updated_columns{expirationdate}
609                     and $updated_columns{expirationdate} eq '' )
610               )
611             {
612                 $self->_set_default_expirationdate;
613             }
614         }
615     }
616
617     $self = $self->SUPER::store;
618 }
619
620 sub _set_default_expirationdate {
621     my $self = shift;
622
623     my $period = C4::Context->preference('DefaultHoldExpirationdatePeriod') || 0;
624     my $timeunit =
625       C4::Context->preference('DefaultHoldExpirationdateUnitOfTime') || 'days';
626
627     $self->expirationdate(
628         dt_from_string( $self->reservedate )->add( $timeunit => $period ) );
629 }
630
631 =head3 _move_to_old
632
633 my $is_moved = $hold->_move_to_old;
634
635 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
636
637 =cut
638
639 sub _move_to_old {
640     my ($self) = @_;
641     my $hold_infos = $self->unblessed;
642     return Koha::Old::Hold->new( $hold_infos )->store;
643 }
644
645 =head3 to_api_mapping
646
647 This method returns the mapping for representing a Koha::Hold object
648 on the API.
649
650 =cut
651
652 sub to_api_mapping {
653     return {
654         reserve_id       => 'hold_id',
655         borrowernumber   => 'patron_id',
656         reservedate      => 'hold_date',
657         biblionumber     => 'biblio_id',
658         branchcode       => 'pickup_library_id',
659         notificationdate => undef,
660         reminderdate     => undef,
661         cancellationdate => 'cancellation_date',
662         reservenotes     => 'notes',
663         found            => 'status',
664         itemnumber       => 'item_id',
665         waitingdate      => 'waiting_date',
666         expirationdate   => 'expiration_date',
667         lowestPriority   => 'lowest_priority',
668         suspend          => 'suspended',
669         suspend_until    => 'suspended_until',
670         itemtype         => 'item_type',
671         item_level_hold  => 'item_level',
672     };
673 }
674
675 =head2 Internal methods
676
677 =head3 _type
678
679 =cut
680
681 sub _type {
682     return 'Reserve';
683 }
684
685 =head1 AUTHORS
686
687 Kyle M Hall <kyle@bywatersolutions.com>
688 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
689 Martin Renvoize <martin.renvoize@ptfs-europe.com>
690
691 =cut
692
693 1;