Bug 12556: Add new "in processing" state to holds
[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
26 use C4::Context qw(preference);
27 use C4::Letters;
28 use C4::Log;
29
30 use Koha::AuthorisedValues;
31 use Koha::DateUtils qw(dt_from_string output_pref);
32 use Koha::Patrons;
33 use Koha::Biblios;
34 use Koha::Items;
35 use Koha::Libraries;
36 use Koha::Old::Holds;
37 use Koha::Calendar;
38
39 use Koha::Exceptions::Hold;
40
41 use base qw(Koha::Object);
42
43 =head1 NAME
44
45 Koha::Hold - Koha Hold object class
46
47 =head1 API
48
49 =head2 Class Methods
50
51 =cut
52
53 =head3 age
54
55 returns the number of days since a hold was placed, optionally
56 using the calendar
57
58 my $age = $hold->age( $use_calendar );
59
60 =cut
61
62 sub age {
63     my ( $self, $use_calendar ) = @_;
64
65     my $today = dt_from_string;
66     my $age;
67
68     if ( $use_calendar ) {
69         my $calendar = Koha::Calendar->new( branchcode => $self->branchcode );
70         $age = $calendar->days_between( dt_from_string( $self->reservedate ), $today );
71     }
72     else {
73         $age = $today->delta_days( dt_from_string( $self->reservedate ) );
74     }
75
76     $age = $age->in_units( 'days' );
77
78     return $age;
79 }
80
81 =head3 suspend_hold
82
83 my $hold = $hold->suspend_hold( $suspend_until_dt );
84
85 =cut
86
87 sub suspend_hold {
88     my ( $self, $dt ) = @_;
89
90     my $date = $dt ? $dt->clone()->truncate( to => 'day' )->datetime : undef;
91
92     if ( $self->is_found ) {    # We can't suspend found holds
93         if ( $self->is_waiting ) {
94             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' );
95         }
96         elsif ( $self->is_in_transit ) {
97             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'T' );
98         }
99         elsif ( $self->is_in_processing ) {
100             Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'P' );
101         }
102         else {
103             Koha::Exceptions::Hold::CannotSuspendFound->throw(
104                       'Unhandled data exception on found hold (id='
105                     . $self->id
106                     . ', found='
107                     . $self->found
108                     . ')' );
109         }
110     }
111
112     $self->suspend(1);
113     $self->suspend_until($date);
114     $self->store();
115
116     logaction( 'HOLDS', 'SUSPEND', $self->reserve_id, Dumper( $self->unblessed ) )
117         if C4::Context->preference('HoldsLog');
118
119     return $self;
120 }
121
122 =head3 resume
123
124 my $hold = $hold->resume();
125
126 =cut
127
128 sub resume {
129     my ( $self ) = @_;
130
131     $self->suspend(0);
132     $self->suspend_until( undef );
133
134     $self->store();
135
136     logaction( 'HOLDS', 'RESUME', $self->reserve_id, Dumper($self->unblessed) )
137         if C4::Context->preference('HoldsLog');
138
139     return $self;
140 }
141
142 =head3 delete
143
144 $hold->delete();
145
146 =cut
147
148 sub delete {
149     my ( $self ) = @_;
150
151     my $deleted = $self->SUPER::delete($self);
152
153     logaction( 'HOLDS', 'DELETE', $self->reserve_id, Dumper($self->unblessed) )
154         if C4::Context->preference('HoldsLog');
155
156     return $deleted;
157 }
158
159 =head3 set_transfer
160
161 =cut
162
163 sub set_transfer {
164     my ( $self ) = @_;
165
166     $self->priority(0);
167     $self->found('T');
168     $self->store();
169
170     return $self;
171 }
172
173 =head3 set_waiting
174
175 =cut
176
177 sub set_waiting {
178     my ( $self ) = @_;
179
180     $self->priority(0);
181
182     my $today = dt_from_string();
183     my $values = {
184         found => 'W',
185         waitingdate => $today->ymd,
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 set_processing
224
225 =cut
226
227 sub set_processing {
228     my ( $self ) = @_;
229
230     $self->priority(0);
231     $self->found('P');
232     $self->store();
233
234     return $self;
235 }
236
237 =head3 is_found
238
239 Returns true if hold is waiting, in transit or in processing
240
241 =cut
242
243 sub is_found {
244     my ($self) = @_;
245
246     return 0 unless $self->found();
247     return 1 if $self->found() eq 'W';
248     return 1 if $self->found() eq 'T';
249     return 1 if $self->found() eq 'P';
250 }
251
252 =head3 is_waiting
253
254 Returns true if hold is a waiting hold
255
256 =cut
257
258 sub is_waiting {
259     my ($self) = @_;
260
261     my $found = $self->found;
262     return $found && $found eq 'W';
263 }
264
265 =head3 is_in_transit
266
267 Returns true if hold is a in_transit hold
268
269 =cut
270
271 sub is_in_transit {
272     my ($self) = @_;
273
274     return 0 unless $self->found();
275     return $self->found() eq 'T';
276 }
277
278 =head3 is_in_processing
279
280 Returns true if hold is a in_processing hold
281
282 =cut
283
284 sub is_in_processing {
285     my ($self) = @_;
286
287     return 0 unless $self->found();
288     return $self->found() eq 'P';
289 }
290
291 =head3 is_cancelable_from_opac
292
293 Returns true if hold is a cancelable hold
294
295 Holds may be only canceled if they are not found.
296
297 This is used from the OPAC.
298
299 =cut
300
301 sub is_cancelable_from_opac {
302     my ($self) = @_;
303
304     return 1 unless $self->is_found();
305     return 0; # if ->is_in_transit or if ->is_waiting or ->is_in_processing
306 }
307
308 =head3 is_at_destination
309
310 Returns true if hold is waiting
311 and the hold's pickup branch matches
312 the hold item's holding branch
313
314 =cut
315
316 sub is_at_destination {
317     my ($self) = @_;
318
319     return $self->is_waiting() && ( $self->branchcode() eq $self->item()->holdingbranch() );
320 }
321
322 =head3 biblio
323
324 Returns the related Koha::Biblio object for this hold
325
326 =cut
327
328 sub biblio {
329     my ($self) = @_;
330
331     $self->{_biblio} ||= Koha::Biblios->find( $self->biblionumber() );
332
333     return $self->{_biblio};
334 }
335
336 =head3 item
337
338 Returns the related Koha::Item object for this Hold
339
340 =cut
341
342 sub item {
343     my ($self) = @_;
344
345     $self->{_item} ||= Koha::Items->find( $self->itemnumber() );
346
347     return $self->{_item};
348 }
349
350 =head3 branch
351
352 Returns the related Koha::Library object for this Hold
353
354 =cut
355
356 sub branch {
357     my ($self) = @_;
358
359     $self->{_branch} ||= Koha::Libraries->find( $self->branchcode() );
360
361     return $self->{_branch};
362 }
363
364 =head3 borrower
365
366 Returns the related Koha::Patron object for this Hold
367
368 =cut
369
370 # FIXME Should be renamed with ->patron
371 sub borrower {
372     my ($self) = @_;
373
374     $self->{_borrower} ||= Koha::Patrons->find( $self->borrowernumber() );
375
376     return $self->{_borrower};
377 }
378
379 =head3 is_suspended
380
381 my $bool = $hold->is_suspended();
382
383 =cut
384
385 sub is_suspended {
386     my ( $self ) = @_;
387
388     return $self->suspend();
389 }
390
391
392 =head3 cancel
393
394 my $cancel_hold = $hold->cancel(
395     {
396         [ charge_cancel_fee => 1||0, ]
397         [ cancellation_reason => $cancellation_reason, ]
398     }
399 );
400
401 Cancel a hold:
402 - The hold will be moved to the old_reserves table with a priority=0
403 - The priority of other holds will be updated
404 - The patron will be charge (see ExpireReservesMaxPickUpDelayCharge) if the charge_cancel_fee parameter is set
405 - The canceled hold will have the cancellation reason added to old_reserves.cancellation_reason if one is passed in
406 - a CANCEL HOLDS log will be done if the pref HoldsLog is on
407
408 =cut
409
410 sub cancel {
411     my ( $self, $params ) = @_;
412     $self->_result->result_source->schema->txn_do(
413         sub {
414             $self->cancellationdate( dt_from_string->strftime( '%Y-%m-%d %H:%M:%S' ) );
415             $self->priority(0);
416             $self->cancellation_reason( $params->{cancellation_reason} );
417             $self->store();
418
419             if ( $params->{cancellation_reason} ) {
420                 my $letter = C4::Letters::GetPreparedLetter(
421                     module                 => 'reserves',
422                     letter_code            => 'HOLD_CANCELLATION',
423                     message_transport_type => 'email',
424                     branchcode             => $self->borrower->branchcode,
425                     lang                   => $self->borrower->lang,
426                     tables => {
427                         branches    => $self->borrower->branchcode,
428                         borrowers   => $self->borrowernumber,
429                         items       => $self->itemnumber,
430                         biblio      => $self->biblionumber,
431                         biblioitems => $self->biblionumber,
432                         reserves    => $self->unblessed,
433                     }
434                 );
435
436                 if ($letter) {
437                     C4::Letters::EnqueueLetter(
438                         {
439                             letter                   => $letter,
440                             borrowernumber         => $self->borrowernumber,
441                             message_transport_type => 'email',
442                         }
443                     );
444                 }
445             }
446
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;