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