Bug 25812: Fines can be displayed on SIP checkin/checkout
[koha.git] / C4 / SIP / ILS.pm
1 #
2 # ILS.pm: Koha ILS interface module
3 #
4
5 package C4::SIP::ILS;
6
7 use warnings;
8 use strict;
9 use C4::SIP::Sip qw( siplog );
10 use Koha::DateUtils qw( dt_from_string output_pref );
11 use Data::Dumper;
12
13 use C4::SIP::ILS::Item;
14 use C4::SIP::ILS::Patron;
15 use C4::SIP::ILS::Transaction;
16 use C4::SIP::ILS::Transaction::Checkout;
17 use C4::SIP::ILS::Transaction::Checkin;
18 use C4::SIP::ILS::Transaction::FeePayment;
19 use C4::SIP::ILS::Transaction::Hold;
20 use C4::SIP::ILS::Transaction::Renew;
21 use C4::SIP::ILS::Transaction::RenewAll;
22
23 my %supports = (
24     'magnetic media'        => 1,
25     'security inhibit'      => 0,
26     'offline operation'     => 0,
27     "patron status request" => 1,
28     "checkout"              => 1,
29     "checkin"               => 1,
30     "block patron"          => 1,
31     "acs status"            => 1,
32     "login"                 => 1,
33     "patron information"    => 1,
34     "end patron session"    => 1,
35     "fee paid"              => 1,
36     "item information"      => 1,
37     "item status update"    => 0,
38     "patron enable"         => 1,
39     "hold"                  => 1,
40     "renew"                 => 1,
41     "renew all"             => 1,
42 );
43
44 sub new {
45     my ($class, $institution) = @_;
46     my $type = ref($class) || $class;
47     my $self = {};
48     siplog("LOG_DEBUG", "new ILS '%s'", $institution->{id});
49     $self->{institution} = $institution;
50     return bless $self, $type;
51 }
52
53 sub find_patron {
54     my $self = shift;
55     return C4::SIP::ILS::Patron->new(@_);
56 }
57
58 sub find_item {
59     my $self = shift;
60     return C4::SIP::ILS::Item->new(@_);
61 }
62
63 sub institution {
64     my $self = shift;
65     return $self->{institution}->{id};  # consider making this return the whole institution
66 }
67
68 sub institution_id {
69     my $self = shift;
70     return $self->{institution}->{id};
71 }
72
73 sub supports {
74     my ($self, $op) = @_;
75     return (exists($supports{$op}) && $supports{$op});
76 }
77
78 sub check_inst_id {
79     my ($self, $id, $whence) = @_;
80     if ($id ne $self->{institution}->{id}) {
81         siplog("LOG_WARNING", "%s: received institution '%s', expected '%s'", $whence, $id, $self->{institution}->{id});
82         # Just an FYI check, we don't expect the user to change location from that in SIPconfig.xml
83     }
84 }
85
86 sub to_bool {
87     my $bool = shift;
88     # If it's defined, and matches a true sort of string, or is
89     # a non-zero number, then it's true.
90     defined($bool) or return;                   # false
91     ($bool =~ /true|y|yes/i) and return 1;      # true
92     return ($bool =~ /^\d+$/ and $bool != 0);   # true for non-zero numbers, false otherwise
93 }
94
95 sub checkout_ok {
96     my $self = shift;
97     return (exists($self->{institution}->{policy}->{checkout})
98             && to_bool($self->{institution}->{policy}->{checkout}));
99 }
100 sub checkin_ok {
101     my $self = shift;
102     return (exists($self->{institution}->{policy}->{checkin})
103             && to_bool($self->{institution}->{policy}->{checkin}));
104 }
105 sub status_update_ok {
106     my $self = shift;
107     return (exists($self->{institution}->{policy}->{status_update})
108             && to_bool($self->{institution}->{policy}->{status_update}));
109 }
110 sub offline_ok {
111     my $self = shift;
112     return (exists($self->{institution}->{policy}->{offline})
113             && to_bool($self->{institution}->{policy}->{offline}));
114 }
115
116 #
117 # Checkout(patron_id, item_id, sc_renew):
118 #    patron_id & item_id are the identifiers send by the terminal
119 #    sc_renew is the renewal policy configured on the terminal
120 # returns a status opject that can be queried for the various bits
121 # of information that the protocol (SIP or NCIP) needs to generate
122 # the response.
123 #
124 sub checkout {
125     my ( $self, $patron_id, $item_id, $sc_renew, $fee_ack, $account, $no_block_due_date ) = @_;
126     my ( $patron, $item, $circ );
127     $circ = C4::SIP::ILS::Transaction::Checkout->new();
128     # BEGIN TRANSACTION
129     $circ->patron( $patron = C4::SIP::ILS::Patron->new($patron_id) );
130     $circ->item( $item     = C4::SIP::ILS::Item->new($item_id) );
131     if ($fee_ack) {
132         $circ->fee_ack($fee_ack);
133     }
134     if ( !$patron ) {
135         $circ->screen_msg("Invalid Patron");
136     }
137     elsif ( !$patron->charge_ok ) {
138         if ($patron->debarred) {
139             $circ->screen_msg("Patron debarred");
140         } elsif ($patron->expired) {
141             $circ->screen_msg("Patron expired on " . output_pref({ dt => dt_from_string( $patron->dateexpiry_iso, 'iso' ), dateonly => 1 }));
142         } elsif ($patron->fine_blocked) {
143             my $message = "Patron has fines";
144             if ($account->{show_outstanding_amount}) {
145                 my $patron_account = Koha::Account->new( { patron_id => $patron->{borrowernumber} });
146                 my $balance = $patron_account->balance;
147                 if ($balance) {
148                     $message .= (" - You owe " . Koha::Number::Price->new( $balance )->format({ with_symbol => 1}) . ".");
149                 }
150             }
151             $circ->screen_msg($message);
152         } else {
153             $circ->screen_msg("Patron blocked");
154         }
155     }
156     elsif ( !$item ) {
157         $circ->screen_msg("Invalid Item");
158     }
159     elsif ( $item->{borrowernumber}
160         && !_ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) )
161     {
162         $circ->screen_msg("Item checked out to another patron");
163     }
164     else {
165         $circ->do_checkout($account, $no_block_due_date);
166         if ( $circ->ok ) {
167
168             # If the item is already associated with this patron, then
169             # we're renewing it.
170             $circ->renew_ok( $item->{borrowernumber}
171                   && _ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) );
172
173             $item->{borrowernumber}   = $patron_id;
174             $item->{due_date} = $circ->{due};
175             push( @{ $patron->{items} }, { barcode => $item_id } );
176             $circ->desensitize( !$item->magnetic_media );
177
178             siplog(
179                 "LOG_DEBUG", "ILS::Checkout: patron %s has checked out %s",
180                 $patron_id, join( ', ', map{ $_->{barcode} } @{ $patron->{items} } )
181             );
182         }
183         else {
184             siplog( "LOG_ERR", "ILS::Checkout Issue failed" );
185         }
186     }
187
188     # END TRANSACTION
189
190     return $circ;
191 }
192
193 sub _ci_cardnumber_cmp {
194     my ( $s1, $s2) = @_;
195     # As the database is case insensitive we need to normalize two strings
196     # before comparing them
197     return ( uc($s1) eq uc($s2) );
198 }
199
200 # wrapper which allows above to be called for testing
201
202 sub test_cardnumber_compare {
203     my ($self, $str1, $str2) = @_;
204     return _ci_cardnumber_cmp($str1, $str2);
205 }
206
207 sub checkin {
208     my ( $self, $item_id, $trans_date, $return_date, $current_loc, $item_props, $cancel, $account ) = @_;
209
210     my $checked_in_ok     = $account->{checked_in_ok};
211     my $cv_triggers_alert = $account->{cv_triggers_alert};
212     my $holds_block_checkin  = $account->{holds_block_checkin};
213
214     my ( $patron, $item, $circ );
215
216     $circ = C4::SIP::ILS::Transaction::Checkin->new();
217
218     # BEGIN TRANSACTION
219     $circ->item( $item = C4::SIP::ILS::Item->new($item_id) );
220
221     my $data;
222     if ($item) {
223         $data = $circ->do_checkin( $current_loc, $return_date, $account );
224     }
225     else {
226         $circ->alert(1);
227         $circ->alert_type(99);
228         $circ->ok( 0 );
229         $circ->screen_msg('Invalid Item');
230         return $circ;
231     }
232
233     if ( !$circ->ok && $circ->alert_type && $circ->alert_type == 98 ) { # data corruption
234         $circ->screen_msg("Checkin failed: data problem");
235         siplog( "LOG_WARNING", "Problem with issue_id in issues and old_issues; check the about page" );
236     } elsif ( $data->{messages}->{ResFound} && !$circ->ok && $holds_block_checkin ) {
237         $circ->screen_msg("Item is on hold, please return to circulation desk");
238         siplog ("LOG_DEBUG", "C4::SIP::ILS::Checkin - item on hold");
239     } elsif ( $data->{messages}->{withdrawn} && !$circ->ok && C4::Context->preference("BlockReturnOfWithdrawnItems") ) {
240             $circ->screen_msg("Item withdrawn, return not allowed");
241             siplog ("LOG_DEBUG", "C4::SIP::ILS::Checkin - item withdrawn");
242     } elsif ( $data->{messages}->{WasLost} && !$circ->ok && C4::Context->preference("BlockReturnOfLostItems") ) {
243             $circ->screen_msg("Item lost, return not allowed");
244             siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - item lost");
245     } elsif ( !$item->{borrowernumber} ) {
246         if ( $checked_in_ok ) { # Mark checkin ok although book not checked out
247             $circ->ok( 1 );
248             siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - using checked_in_ok");
249         } else {
250             $circ->screen_msg("Item not checked out");
251             siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - item not checked out");
252         }
253     } elsif ( $circ->ok ) {
254         $circ->patron( $patron = C4::SIP::ILS::Patron->new( { borrowernumber => $item->{borrowernumber} } ) );
255         delete $item->{borrowernumber};
256         delete $item->{due_date};
257         $patron->{items} = [ grep { $_ ne $item_id } @{ $patron->{items} } ];
258         # Check for overdue fines to display
259         if ($account->{show_outstanding_amount}) {
260             my $kohaitem = Koha::Items->find( { barcode => $item_id } );
261             if ($kohaitem) {
262                 my $charges = Koha::Account::Lines->search(
263                     {
264                         borrowernumber    => $patron->{borrowernumber},
265                         amountoutstanding => { '>' => 0 },
266                         debit_type_code   => [ 'OVERDUE' ],
267                         itemnumber        => $kohaitem->itemnumber
268                     },
269                 );
270                 if ($charges) {
271                     $circ->screen_msg("You owe " . Koha::Number::Price->new( $charges->total_outstanding )->format({ with_symbol => 1}) . " for this item.");
272                 }
273             }
274         }
275     } else {
276         # Checkin failed: Wrongbranch or withdrawn?
277         # Bug 10748 with pref BlockReturnOfLostItems adds another case to come
278         # here: returning a lost item when the pref is set.
279         $circ->screen_msg("Checkin failed");
280         siplog( "LOG_WARNING", "Checkin failed: probably for Wrongbranch or withdrawn" );
281     }
282
283     return $circ;
284 }
285
286 # If the ILS caches patron information, this lets it free
287 # it up
288 sub end_patron_session {
289     my ($self, $patron_id) = @_;
290
291     # success?, screen_msg, print_line
292     return (1, 'Thank you !', '');
293 }
294
295 sub pay_fee {
296     my ($self, $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, $is_writeoff, $disallow_overpayment, $register_id) = @_;
297
298     my $trans = C4::SIP::ILS::Transaction::FeePayment->new();
299
300     $trans->transaction_id($trans_id);
301     my $patron;
302     $trans->patron($patron = C4::SIP::ILS::Patron->new($patron_id));
303     if (!$patron) {
304         $trans->screen_msg('Invalid patron barcode.');
305         return $trans;
306     }
307     my $trans_result = $trans->pay( $patron->{borrowernumber}, $fee_amt, $pay_type, $fee_id, $is_writeoff, $disallow_overpayment, $register_id );
308     my $ok = $trans_result->{ok};
309     $trans->ok($ok);
310
311     return {
312         status       => $trans,
313         pay_response => $trans_result->{pay_response}
314     };
315 }
316
317 sub add_hold {
318     my ($self, $patron_id, $patron_pwd, $item_id, $title_id,
319         $expiry_date, $pickup_location, $hold_type, $fee_ack) = @_;
320     my ($patron, $item);
321
322         my $trans = C4::SIP::ILS::Transaction::Hold->new();
323
324     $patron = C4::SIP::ILS::Patron->new( $patron_id );
325     if ( !$patron ) {
326         $trans->screen_msg("Invalid patron barcode.");
327         return $trans;
328     }
329
330         unless ($item = C4::SIP::ILS::Item->new($item_id || $title_id)) {
331                 $trans->screen_msg("No such item.");
332                 return $trans;
333         }
334
335     if ( $patron->holds_blocked_by_excessive_fees() ) {
336         $trans->screen_msg("Excessive fees blocking placement of hold.");
337     }
338
339    if ($item->fee and $fee_ack ne 'Y') {
340                 $trans->screen_msg = "Fee required to place hold.";
341                 return $trans;
342     }
343
344     my $hold = {
345         item_id         => $item->id,
346         patron_id       => $patron->id,
347         expiration_date => $expiry_date,
348         pickup_location => $pickup_location,
349         hold_type       => $hold_type,
350     };
351
352     $trans->ok(1);
353     $trans->patron($patron);
354     $trans->item($item);
355     $trans->pickup_location($pickup_location);
356         $trans->do_hold;
357
358     push(@{$item->hold_queue},     $hold);
359     push(@{$patron->{hold_items}}, $hold);
360
361     return $trans;
362 }
363
364 sub cancel_hold {
365     my ($self, $patron_id, $patron_pwd, $item_id, $title_id) = @_;
366     my ($patron, $item, $hold);
367
368         my $trans = C4::SIP::ILS::Transaction::Hold->new();
369
370     $patron = C4::SIP::ILS::Patron->new( $patron_id );
371     if (!$patron) {
372                 $trans->screen_msg("Invalid patron barcode.");
373                 return $trans;
374     }
375
376     unless ($item = C4::SIP::ILS::Item->new($item_id || $title_id)) {
377                 $trans->screen_msg("No such item.");
378                 return $trans;
379     }
380
381     $trans->patron($patron);
382     $trans->item($item);
383         $trans->drop_hold;
384         unless ($trans->ok) {
385                 $trans->screen_msg("Error with transaction drop_hold: " . $trans->screen_msg);
386                 return $trans;
387         }
388     # Remove the hold from the patron's record first
389     $patron->drop_hold($item_id); # different than the transaction drop!
390
391     # Now, remove it from the item record.  If it was on the patron
392     # record but not on the item record, we'll treat that as success.
393     foreach my $i (0 .. scalar @{$item->hold_queue}) {
394                 $hold = $item->hold_queue->[$i];
395                 if ($item->barcode_is_borrowernumber($patron->id, $hold->{borrowernumber})) {
396                     # found it: delete it.
397                     splice @{$item->hold_queue}, $i, 1;
398                     last;               # ?? should we keep going, in case there are multiples
399                 }
400     }
401
402     $trans->screen_msg("Hold Cancelled.");
403
404     return $trans;
405 }
406
407
408 # The patron and item id's can't be altered, but the
409 # date, location, and type can.
410 sub alter_hold {
411     my ($self, $patron_id, $patron_pwd, $item_id, $title_id,
412         $expiry_date, $pickup_location, $hold_type, $fee_ack) = @_;
413     my ($patron, $item);
414     my $hold;
415     my $trans;
416
417     $trans = C4::SIP::ILS::Transaction::Hold->new();
418
419     # BEGIN TRANSACTION
420     $patron = C4::SIP::ILS::Patron->new( $patron_id );
421     unless ($patron) {
422                 $trans->screen_msg("Invalid patron barcode: '$patron_id'.");
423                 return $trans;
424     }
425
426     foreach my $i (0 .. scalar @{$patron->{hold_items}}) {
427                 $hold = $patron->{hold_items}[$i];
428
429         if ($hold->{item_id} eq $item_id) {
430             # Found it.  So fix it.
431             $hold->{expiration_date} = $expiry_date     if $expiry_date;
432             $hold->{pickup_location} = $pickup_location if $pickup_location;
433             $hold->{hold_type}       = $hold_type       if $hold_type;
434                 $trans->change_hold();
435             # $trans->ok(1);
436             $trans->screen_msg("Hold updated.");
437             $trans->patron($patron);
438             $trans->item(C4::SIP::ILS::Item->new( $hold->{item_id}));
439             last;
440         }
441     }
442
443     # The same hold structure is linked into both the patron's
444     # list of hold items and into the queue of outstanding holds
445     # for the item, so we don't need to search the hold queue for
446     # the item, since it's already been updated by the patron code.
447
448     if (!$trans->ok) {
449                 $trans->screen_msg("No such outstanding hold.");
450     }
451
452     return $trans;
453 }
454
455 sub renew {
456     my ($self, $patron_id, $patron_pwd, $item_id, $title_id,
457         $no_block, $nb_due_date, $third_party,
458         $item_props, $fee_ack) = @_;
459     my ($patron, $item);
460     my $trans;
461
462     $trans = C4::SIP::ILS::Transaction::Renew->new();
463     $trans->patron($patron = C4::SIP::ILS::Patron->new( $patron_id ));
464
465     if (!$patron) {
466                 $trans->screen_msg("Invalid patron barcode.");
467                 return $trans;
468     } elsif (!$patron->renew_ok) {
469                 $trans->screen_msg("Renewals not allowed.");
470                 return $trans;
471     }
472
473         # Previously: renewing a title, rather than an item (sort of)
474         # This is gross, but in a real ILS it would be better
475
476     # if (defined($title_id)) {
477         #       foreach my $i (@{$patron->{items}}) {
478         #               $item = new ILS::Item $i;
479         #               last if ($title_id eq $item->title_id);
480         #               $item = undef;
481         #       }
482     # } else {
483                 my $j = 0;
484                 my $count = scalar @{$patron->{items}};
485                 foreach my $i (@{$patron->{items}}) {
486             unless (defined $i->{barcode}) {    # FIXME: using data instead of objects may violate the abstraction layer
487                 siplog("LOG_ERR", "No barcode for item %s of %s: $item_id", $j+1, $count);
488                 next;
489             }
490             siplog("LOG_DEBUG", "checking item %s of %s: $item_id vs. %s", ++$j, $count, $i->{barcode});
491             if ($i->{barcode} eq $item_id) {
492                                 # We have it checked out
493                                 $item = C4::SIP::ILS::Item->new( $item_id );
494                                 last;
495                         }
496                 }
497     # }
498
499     $trans->item($item);
500
501     if (!defined($item)) {
502                 $trans->screen_msg("Item not checked out to " . $patron->name);     # not checked out to $patron_id
503         $trans->ok(0);
504     } else {
505         $trans->do_renew();
506         if ($trans->renewal_ok()) {
507             $item->{due_date} = $trans->{due};
508             $trans->desensitize(0);
509         }
510     }
511
512     return $trans;
513 }
514
515 sub renew_all {
516     my ($self, $patron_id, $patron_pwd, $fee_ack) = @_;
517     my ($patron, $item_id);
518     my $trans;
519
520     $trans = C4::SIP::ILS::Transaction::RenewAll->new();
521
522     $trans->patron($patron = C4::SIP::ILS::Patron->new( $patron_id ));
523     if (defined $patron) {
524         siplog("LOG_DEBUG", "ILS::renew_all: patron '%s': renew_ok: %s", $patron->name, $patron->renew_ok);
525     } else {
526         siplog("LOG_DEBUG", "ILS::renew_all: Invalid patron id: '%s'", $patron_id);
527     }
528
529     if (!$patron) {
530                 $trans->screen_msg("Invalid patron barcode.");
531                 return $trans;
532     } elsif (!$patron->renew_ok) {
533                 $trans->screen_msg("Renewals not allowed.");
534                 return $trans;
535     }
536
537         $trans->do_renew_all;
538     $trans->ok(1);
539     return $trans;
540 }
541
542 1;
543 __END__
544