Bug 29300: REVERT
[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::Log;
29
30 use Koha::DateUtils qw(dt_from_string output_pref);
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         else {
99             Koha::Exceptions::Hold::CannotSuspendFound->throw(
100                       'Unhandled data exception on found hold (id='
101                     . $self->id
102                     . ', found='
103                     . $self->found
104                     . ')' );
105         }
106     }
107
108     $self->suspend(1);
109     $self->suspend_until($date);
110     $self->store();
111
112     logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, Dumper( $self->unblessed ) )
113         if C4::Context->preference('HoldsLog');
114
115     return $self;
116 }
117
118 =head3 resume
119
120 my $hold = $hold->resume();
121
122 =cut
123
124 sub resume {
125     my ( $self ) = @_;
126
127     $self->suspend(0);
128     $self->suspend_until( undef );
129
130     $self->store();
131
132     logaction( 'HOLDS', 'RESUME', $self->reserve_id, Dumper($self->unblessed) )
133         if C4::Context->preference('HoldsLog');
134
135     return $self;
136 }
137
138 =head3 delete
139
140 $hold->delete();
141
142 =cut
143
144 sub delete {
145     my ( $self ) = @_;
146
147     my $deleted = $self->SUPER::delete($self);
148
149     logaction( 'HOLDS', 'DELETE', $self->reserve_id, Dumper($self->unblessed) )
150         if C4::Context->preference('HoldsLog');
151
152     return $deleted;
153 }
154
155 =head3 set_waiting
156
157 =cut
158
159 sub set_waiting {
160     my ( $self, $transferToDo ) = @_;
161
162     $self->priority(0);
163
164     if ($transferToDo) {
165         $self->found('T')->store();
166         return $self;
167     }
168
169     my $today = dt_from_string();
170     my $values = {
171         found => 'W',
172         waitingdate => $today->ymd,
173     };
174
175     my $requested_expiration;
176     if ($self->expirationdate) {
177         $requested_expiration = dt_from_string($self->expirationdate);
178     }
179
180     my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
181     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
182     my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
183
184     my $expirationdate = $today->clone;
185     $expirationdate->add(days => $max_pickup_delay);
186
187     if ( C4::Context->preference("ExcludeHolidaysFromMaxPickUpDelay") ) {
188         $expirationdate = $calendar->days_forward( dt_from_string(), $max_pickup_delay );
189     }
190
191     # If patron's requested expiration date is prior to the
192     # calculated one, we keep the patron's one.
193     my $cmp = $requested_expiration ? DateTime->compare($requested_expiration, $expirationdate) : 0;
194     $values->{expirationdate} = $cmp == -1 ? $requested_expiration->ymd : $expirationdate->ymd;
195
196     $self->set($values)->store();
197
198     return $self;
199 }
200
201 =head3 is_pickup_location_valid
202
203     if ($hold->is_pickup_location_valid({ library_id => $library->id }) ) {
204         ...
205     }
206
207 Returns a I<boolean> representing if the passed pickup location is valid for the hold.
208 It throws a I<Koha::Exceptions::_MissingParameter> if the library_id parameter is not
209 passed.
210
211 =cut
212
213 sub is_pickup_location_valid {
214     my ( $self, $params ) = @_;
215
216     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
217         unless $params->{library_id};
218
219     my @pickup_locations;
220
221     if ( $self->itemnumber ) { # item-level
222         @pickup_locations = $self->item->pickup_locations({ patron => $self->patron });
223     }
224     else { # biblio-level
225         @pickup_locations = $self->biblio->pickup_locations({ patron => $self->patron });
226     }
227
228     return any { $_->branchcode eq $params->{library_id} } @pickup_locations;
229 }
230
231 =head3 set_pickup_location
232
233     $hold->set_pickup_location({ library_id => $library->id });
234
235 Updates the hold pickup location. It throws a I<Koha::Exceptions::Hold::InvalidPickupLocation> if
236 the passed pickup location is not valid.
237
238 =cut
239
240 sub set_pickup_location {
241     my ( $self, $params ) = @_;
242
243     Koha::Exceptions::MissingParameter->throw('The library_id parameter is mandatory')
244         unless $params->{library_id};
245
246     if ( $self->is_pickup_location_valid({ library_id => $params->{library_id} }) ) {
247         # all good, set the new pickup location
248         $self->branchcode( $params->{library_id} )->store;
249     }
250     else {
251         Koha::Exceptions::Hold::InvalidPickupLocation->throw;
252     }
253
254     return $self;
255 }
256
257 =head3 set_processing
258
259 $hold->set_processing;
260
261 Mark the hold as in processing.
262
263 =cut
264
265 sub set_processing {
266     my ( $self ) = @_;
267
268     $self->priority(0);
269     $self->found('P');
270     $self->store();
271
272     return $self;
273 }
274
275 =head3 is_found
276
277 Returns true if hold is a waiting or in transit
278
279 =cut
280
281 sub is_found {
282     my ($self) = @_;
283
284     return 0 unless $self->found();
285     return 1 if $self->found() eq 'W';
286     return 1 if $self->found() eq 'T';
287 }
288
289 =head3 is_waiting
290
291 Returns true if hold is a waiting hold
292
293 =cut
294
295 sub is_waiting {
296     my ($self) = @_;
297
298     my $found = $self->found;
299     return $found && $found eq 'W';
300 }
301
302 =head3 is_in_transit
303
304 Returns true if hold is a in_transit hold
305
306 =cut
307
308 sub is_in_transit {
309     my ($self) = @_;
310
311     return 0 unless $self->found();
312     return $self->found() eq 'T';
313 }
314
315 =head3 is_cancelable_from_opac
316
317 Returns true if hold is a cancelable hold
318
319 Holds may be only canceled if they are not found.
320
321 This is used from the OPAC.
322
323 =cut
324
325 sub is_cancelable_from_opac {
326     my ($self) = @_;
327
328     return 1 unless $self->is_found();
329     return 0; # if ->is_in_transit or if ->is_waiting
330 }
331
332 =head3 is_at_destination
333
334 Returns true if hold is waiting
335 and the hold's pickup branch matches
336 the hold item's holding branch
337
338 =cut
339
340 sub is_at_destination {
341     my ($self) = @_;
342
343     return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
344 }
345
346 =head3 biblio
347
348 Returns the related Koha::Biblio object for this hold
349
350 =cut
351
352 sub biblio {
353     my ($self) = @_;
354
355     $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
356
357     return $self->{_biblio};
358 }
359
360 =head3 patron
361
362 Returns the related Koha::Patron object for this hold
363
364 =cut
365
366 sub patron {
367     my ($self) = @_;
368
369     my $patron_rs = $self->_result->patron;
370     return Koha::Patron->_new_from_dbic($patron_rs);
371 }
372
373 =head3 item
374
375 Returns the related Koha::Item object for this Hold
376
377 =cut
378
379 sub item {
380     my ($self) = @_;
381
382     $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
383
384     return $self->{_item};
385 }
386
387 =head3 branch
388
389 Returns the related Koha::Library object for this Hold
390
391 =cut
392
393 sub branch {
394     my ($self) = @_;
395
396     $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
397
398     return $self->{_branch};
399 }
400
401 =head3 borrower
402
403 Returns the related Koha::Patron object for this Hold
404
405 =cut
406
407 # FIXME Should be renamed with ->patron
408 sub borrower {
409     my ($self) = @_;
410
411     $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
412
413     return $self->{_borrower};
414 }
415
416 =head3 is_suspended
417
418 my $bool = $hold->is_suspended();
419
420 =cut
421
422 sub is_suspended {
423     my ( $self ) = @_;
424
425     return $self->suspend();
426 }
427
428
429 =head3 cancel
430
431 my $cancel_hold = $hold->cancel();
432
433 Cancel a hold:
434 - The hold will be moved to the old_reserves table with a priority=0
435 - The priority of other holds will be updated
436 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
437 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
438
439 =cut
440
441 sub cancel {
442     my ( $self, $params ) = @_;
443     $self->_result->result_source->schema->txn_do(
444         sub {
445             $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
446             $self->priority(0);
447             $self->_move_to_old;
448             $self->SUPER::delete(); # Do not add a DELETE log
449
450             # now fix the priority on the others....
451             C4::Reserves::_FixPriority({ biblionumber => $self->biblionumber });
452
453             # and, if desired, charge a cancel fee
454             my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
455             if ( $charge && $params->{'charge_cancel_fee'} ) {
456                 my $account =
457                   Koha::Account->new( { patron_id => $self->borrowernumber } );
458                 $account->add_debit(
459                     {
460                         amount     => $charge,
461                         user_id    => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
462                         interface  => C4::Context->interface,
463                         library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
464                         type       => 'RESERVE_EXPIRED',
465                         item_id    => $self->itemnumber
466                     }
467                 );
468             }
469
470             C4::Log::logaction( 'HOLDS', 'CANCEL', $self->reserve_id, Dumper($self->unblessed) )
471                 if C4::Context->preference('HoldsLog');
472         }
473     );
474     return $self;
475 }
476
477 =head3 _move_to_old
478
479 my $is_moved = $hold->_move_to_old;
480
481 Move a hold to the old_reserve table following the same pattern as Koha::Patron->move_to_deleted
482
483 =cut
484
485 sub _move_to_old {
486     my ($self) = @_;
487     my $hold_infos = $self->unblessed;
488     return Koha::Old::Hold->new( $hold_infos )->store;
489 }
490
491 =head3 to_api_mapping
492
493 This method returns the mapping for representing a Koha::Hold object
494 on the API.
495
496 =cut
497
498 sub to_api_mapping {
499     return {
500         reserve_id       => 'hold_id',
501         borrowernumber   => 'patron_id',
502         reservedate      => 'hold_date',
503         biblionumber     => 'biblio_id',
504         branchcode       => 'pickup_library_id',
505         notificationdate => undef,
506         reminderdate     => undef,
507         cancellationdate => 'cancellation_date',
508         reservenotes     => 'notes',
509         found            => 'status',
510         itemnumber       => 'item_id',
511         waitingdate      => 'waiting_date',
512         expirationdate   => 'expiration_date',
513         lowestPriority   => 'lowest_priority',
514         suspend          => 'suspended',
515         suspend_until    => 'suspended_until',
516         itemtype         => 'item_type',
517         item_level_hold  => 'item_level',
518     };
519 }
520
521 =head2 Internal methods
522
523 =head3 _type
524
525 =cut
526
527 sub _type {
528     return 'Reserve';
529 }
530
531 =head1 AUTHORS
532
533 Kyle M Hall <kyle@bywatersolutions.com>
534 Jonathan Druart <jonathan.druart@bugs.koha-community.org>
535 Martin Renvoize <martin.renvoize@ptfs-europe.com>
536
537 =cut
538
539 1;