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