Bug 34328: (follow-up) Add description to en_GB
[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     my @blocked_item_types;
128     if (defined $account->{blocked_item_types}) {
129         @blocked_item_types = split /\|/, $account->{blocked_item_types};
130     }
131     $circ = C4::SIP::ILS::Transaction::Checkout->new();
132     # BEGIN TRANSACTION
133     $circ->patron( $patron = C4::SIP::ILS::Patron->new($patron_id) );
134     $circ->item( $item     = C4::SIP::ILS::Item->new($item_id) );
135     if ($fee_ack) {
136         $circ->fee_ack($fee_ack);
137     }
138     if ( !$patron ) {
139         $circ->screen_msg("Invalid Patron");
140     }
141     elsif ( !$patron->charge_ok ) {
142         if ($patron->debarred) {
143             $circ->screen_msg("Patron debarred");
144         } elsif ($patron->expired) {
145             $circ->screen_msg("Patron expired on " . output_pref({ dt => dt_from_string( $patron->dateexpiry_iso, 'iso' ), dateonly => 1 }));
146         } elsif ($patron->fine_blocked) {
147             my $message = "Patron has fines";
148             if ($account->{show_outstanding_amount}) {
149                 my $patron_account = Koha::Account->new( { patron_id => $patron->{borrowernumber} });
150                 my $balance = $patron_account->balance;
151                 if ($balance) {
152                     $message .= (" - You owe " . Koha::Number::Price->new( $balance )->format({ with_symbol => 1}) . ".");
153                 }
154             }
155             $circ->screen_msg($message);
156         } else {
157             $circ->screen_msg("Patron blocked");
158         }
159     }
160     elsif ( !$item ) {
161         $circ->screen_msg("Invalid Item");
162     }
163     elsif ( $item->{borrowernumber}
164         && !_ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) )
165     {
166         $circ->screen_msg("Item checked out to another patron");
167     }
168     elsif (grep { $_ eq $item->{itemtype} } @blocked_item_types) {
169         $circ->screen_msg("Item type cannot be checked out at this checkout location");
170     }
171     else {
172         $circ->do_checkout($account, $no_block_due_date);
173         if ( $circ->ok ) {
174
175             # If the item is already associated with this patron, then
176             # we're renewing it.
177             $circ->renew_ok( $item->{borrowernumber}
178                   && _ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) );
179
180             $item->{borrowernumber}   = $patron_id;
181             $item->{due_date} = $circ->{due};
182             push( @{ $patron->{items} }, { barcode => $item_id } );
183             $circ->desensitize( !$item->magnetic_media );
184
185             siplog(
186                 "LOG_DEBUG", "ILS::Checkout: patron %s has checked out %s",
187                 $patron_id, join( ', ', map{ $_->{barcode} } @{ $patron->{items} } )
188             );
189         }
190         else {
191             siplog( "LOG_ERR", "ILS::Checkout Issue failed" );
192         }
193     }
194
195     # END TRANSACTION
196
197     return $circ;
198 }
199
200 sub _ci_cardnumber_cmp {
201     my ( $s1, $s2) = @_;
202     # As the database is case insensitive we need to normalize two strings
203     # before comparing them
204     return ( uc($s1) eq uc($s2) );
205 }
206
207 # wrapper which allows above to be called for testing
208
209 sub test_cardnumber_compare {
210     my ($self, $str1, $str2) = @_;
211     return _ci_cardnumber_cmp($str1, $str2);
212 }
213
214 sub checkin {
215     my ( $self, $item_id, $trans_date, $return_date, $current_loc, $item_props, $cancel, $account ) = @_;
216
217     my $checked_in_ok     = $account->{checked_in_ok};
218     my $cv_triggers_alert = $account->{cv_triggers_alert};
219     my $holds_block_checkin  = $account->{holds_block_checkin};
220
221     my ( $patron, $item, $circ );
222
223     $circ = C4::SIP::ILS::Transaction::Checkin->new();
224
225     # BEGIN TRANSACTION
226     $circ->item( $item = C4::SIP::ILS::Item->new($item_id) );
227
228     my $data;
229     if ($item) {
230         $data = $circ->do_checkin( $current_loc, $return_date, $account );
231     }
232     else {
233         $circ->alert(1);
234         $circ->alert_type(99);
235         $circ->ok( 0 );
236         $circ->screen_msg('Invalid Item');
237         return $circ;
238     }
239
240     if ( !$circ->ok && $circ->alert_type && $circ->alert_type == 98 ) { # data corruption
241         $circ->screen_msg("Checkin failed: data problem");
242         siplog( "LOG_WARNING", "Problem with issue_id in issues and old_issues; check the about page" );
243     } elsif ( $data->{messages}->{ResFound} && !$circ->ok && $holds_block_checkin ) {
244         $circ->screen_msg("Item is on hold, please return to circulation desk");
245         siplog ("LOG_DEBUG", "C4::SIP::ILS::Checkin - item on hold");
246     } elsif ( $data->{messages}->{withdrawn} && !$circ->ok && C4::Context->preference("BlockReturnOfWithdrawnItems") ) {
247             $circ->screen_msg("Item withdrawn, return not allowed");
248             siplog ("LOG_DEBUG", "C4::SIP::ILS::Checkin - item withdrawn");
249     } elsif ( $data->{messages}->{WasLost} && !$circ->ok && C4::Context->preference("BlockReturnOfLostItems") ) {
250             $circ->screen_msg("Item lost, return not allowed");
251             siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - item lost");
252     } elsif ( !$item->{borrowernumber} ) {
253         if ( $checked_in_ok ) { # Mark checkin ok although book not checked out
254             $circ->ok( 1 );
255             siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - using checked_in_ok");
256         } else {
257             $circ->screen_msg("Item not checked out");
258             siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - item not checked out");
259         }
260     } elsif ( $circ->ok ) {
261         $circ->patron( $patron = C4::SIP::ILS::Patron->new( { borrowernumber => $item->{borrowernumber} } ) );
262         delete $item->{borrowernumber};
263         delete $item->{due_date};
264         $patron->{items} = [ grep { $_ ne $item_id } @{ $patron->{items} } ];
265         # Check for overdue fines to display
266         if ($account->{show_outstanding_amount}) {
267             my $kohaitem = Koha::Items->find( { barcode => $item_id } );
268             if ($kohaitem) {
269                 my $charges = Koha::Account::Lines->search(
270                     {
271                         borrowernumber    => $patron->{borrowernumber},
272                         amountoutstanding => { '>' => 0 },
273                         debit_type_code   => [ 'OVERDUE' ],
274                         itemnumber        => $kohaitem->itemnumber
275                     },
276                 );
277                 if ($charges) {
278                     $circ->screen_msg("You owe " . Koha::Number::Price->new( $charges->total_outstanding )->format({ with_symbol => 1}) . " for this item.");
279                 }
280             }
281         }
282     } else {
283         # Checkin failed: Wrongbranch or withdrawn?
284         # Bug 10748 with pref BlockReturnOfLostItems adds another case to come
285         # here: returning a lost item when the pref is set.
286         $circ->screen_msg("Checkin failed");
287         siplog( "LOG_WARNING", "Checkin failed: probably for Wrongbranch or withdrawn" );
288     }
289
290     return $circ;
291 }
292
293 # If the ILS caches patron information, this lets it free
294 # it up
295 sub end_patron_session {
296     my ($self, $patron_id) = @_;
297
298     # success?, screen_msg, print_line
299     return (1, 'Thank you !', '');
300 }
301
302 sub pay_fee {
303     my ($self, $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, $is_writeoff, $disallow_overpayment, $register_id) = @_;
304
305     my $trans = C4::SIP::ILS::Transaction::FeePayment->new();
306
307     $trans->transaction_id($trans_id);
308     my $patron;
309     $trans->patron($patron = C4::SIP::ILS::Patron->new($patron_id));
310     if (!$patron) {
311         $trans->screen_msg('Invalid patron barcode.');
312         return $trans;
313     }
314     my $trans_result = $trans->pay( $patron->{borrowernumber}, $fee_amt, $pay_type, $fee_id, $is_writeoff, $disallow_overpayment, $register_id );
315     my $ok = $trans_result->{ok};
316     $trans->ok($ok);
317
318     return {
319         status       => $trans,
320         pay_response => $trans_result->{pay_response},
321         error        => $trans_result->{error},
322     };
323 }
324
325 sub add_hold {
326     my ($self, $patron_id, $patron_pwd, $item_id, $title_id,
327         $expiry_date, $pickup_location, $hold_type, $fee_ack) = @_;
328     my ($patron, $item);
329
330         my $trans = C4::SIP::ILS::Transaction::Hold->new();
331
332     $patron = C4::SIP::ILS::Patron->new( $patron_id );
333     if ( !$patron ) {
334         $trans->screen_msg("Invalid patron barcode.");
335         return $trans;
336     }
337
338         unless ($item = C4::SIP::ILS::Item->new($item_id || $title_id)) {
339                 $trans->screen_msg("No such item.");
340                 return $trans;
341         }
342
343     if ( $patron->holds_blocked_by_excessive_fees() ) {
344         $trans->screen_msg("Excessive fees blocking placement of hold.");
345     }
346
347    if ($item->fee and $fee_ack ne 'Y') {
348                 $trans->screen_msg = "Fee required to place hold.";
349                 return $trans;
350     }
351
352     my $hold = {
353         item_id         => $item->id,
354         patron_id       => $patron->id,
355         expiration_date => $expiry_date,
356         pickup_location => $pickup_location,
357         hold_type       => $hold_type,
358     };
359
360     $trans->ok(1);
361     $trans->patron($patron);
362     $trans->item($item);
363     $trans->pickup_location($pickup_location);
364         $trans->do_hold;
365
366     push(@{$item->hold_queue},     $hold);
367     push(@{$patron->{hold_items}}, $hold);
368
369     return $trans;
370 }
371
372 sub cancel_hold {
373     my ($self, $patron_id, $patron_pwd, $item_id, $title_id) = @_;
374     my ($patron, $item, $hold);
375
376         my $trans = C4::SIP::ILS::Transaction::Hold->new();
377
378     $patron = C4::SIP::ILS::Patron->new( $patron_id );
379     if (!$patron) {
380                 $trans->screen_msg("Invalid patron barcode.");
381                 return $trans;
382     }
383
384     unless ($item = C4::SIP::ILS::Item->new($item_id || $title_id)) {
385                 $trans->screen_msg("No such item.");
386                 return $trans;
387     }
388
389     $trans->patron($patron);
390     $trans->item($item);
391         $trans->drop_hold;
392         unless ($trans->ok) {
393                 $trans->screen_msg("Error with transaction drop_hold: " . $trans->screen_msg);
394                 return $trans;
395         }
396     # Remove the hold from the patron's record first
397     $patron->drop_hold($item_id); # different than the transaction drop!
398
399     # Now, remove it from the item record.  If it was on the patron
400     # record but not on the item record, we'll treat that as success.
401     foreach my $i (0 .. scalar @{$item->hold_queue}) {
402                 $hold = $item->hold_queue->[$i];
403                 if ($item->barcode_is_borrowernumber($patron->id, $hold->{borrowernumber})) {
404                     # found it: delete it.
405                     splice @{$item->hold_queue}, $i, 1;
406                     last;               # ?? should we keep going, in case there are multiples
407                 }
408     }
409
410     $trans->screen_msg("Hold Cancelled.");
411
412     return $trans;
413 }
414
415
416 # The patron and item id's can't be altered, but the
417 # date, location, and type can.
418 sub alter_hold {
419     my ($self, $patron_id, $patron_pwd, $item_id, $title_id,
420         $expiry_date, $pickup_location, $hold_type, $fee_ack) = @_;
421     my ($patron, $item);
422     my $hold;
423     my $trans;
424
425     $trans = C4::SIP::ILS::Transaction::Hold->new();
426
427     # BEGIN TRANSACTION
428     $patron = C4::SIP::ILS::Patron->new( $patron_id );
429     unless ($patron) {
430                 $trans->screen_msg("Invalid patron barcode: '$patron_id'.");
431                 return $trans;
432     }
433
434     foreach my $i (0 .. scalar @{$patron->{hold_items}}) {
435                 $hold = $patron->{hold_items}[$i];
436
437         if ($hold->{item_id} eq $item_id) {
438             # Found it.  So fix it.
439             $hold->{expiration_date} = $expiry_date     if $expiry_date;
440             $hold->{pickup_location} = $pickup_location if $pickup_location;
441             $hold->{hold_type}       = $hold_type       if $hold_type;
442                 $trans->change_hold();
443             # $trans->ok(1);
444             $trans->screen_msg("Hold updated.");
445             $trans->patron($patron);
446             $trans->item(C4::SIP::ILS::Item->new( $hold->{item_id}));
447             last;
448         }
449     }
450
451     # The same hold structure is linked into both the patron's
452     # list of hold items and into the queue of outstanding holds
453     # for the item, so we don't need to search the hold queue for
454     # the item, since it's already been updated by the patron code.
455
456     if (!$trans->ok) {
457                 $trans->screen_msg("No such outstanding hold.");
458     }
459
460     return $trans;
461 }
462
463 sub renew {
464     my ($self, $patron_id, $patron_pwd, $item_id, $title_id,
465         $no_block, $nb_due_date, $third_party,
466         $item_props, $fee_ack) = @_;
467     my ($patron, $item);
468     my $trans;
469
470     $trans = C4::SIP::ILS::Transaction::Renew->new();
471     $trans->patron($patron = C4::SIP::ILS::Patron->new( $patron_id ));
472     if (!$patron) {
473                 $trans->screen_msg("Invalid patron barcode.");
474                 return $trans;
475     } elsif (!$patron->renew_ok) {
476                 $trans->screen_msg("Renewals not allowed.");
477                 return $trans;
478     }
479
480         # Previously: renewing a title, rather than an item (sort of)
481         # This is gross, but in a real ILS it would be better
482
483     # if (defined($title_id)) {
484         #       foreach my $i (@{$patron->{items}}) {
485         #               $item = new ILS::Item $i;
486         #               last if ($title_id eq $item->title_id);
487         #               $item = undef;
488         #       }
489     # } else {
490                 my $j = 0;
491                 my $count = scalar @{$patron->{items}};
492                 foreach my $i (@{$patron->{items}}) {
493             unless (defined $i->{barcode}) {    # FIXME: using data instead of objects may violate the abstraction layer
494                 siplog("LOG_ERR", "No barcode for item %s of %s: $item_id", $j+1, $count);
495                 next;
496             }
497             siplog("LOG_DEBUG", "checking item %s of %s: $item_id vs. %s", ++$j, $count, $i->{barcode});
498             if ($i->{barcode} eq $item_id) {
499                                 # We have it checked out
500                                 $item = C4::SIP::ILS::Item->new( $item_id );
501                                 last;
502                         }
503                 }
504     # }
505
506     $trans->item($item);
507     if ($fee_ack) {
508         $trans->fee_ack($fee_ack);
509     }
510
511     if (!defined($item)) {
512                 $trans->screen_msg("Item not checked out to " . $patron->name);     # not checked out to $patron_id
513         $trans->ok(0);
514     } else {
515         $trans->do_renew();
516         if ($trans->renewal_ok()) {
517             $item->{due_date} = $trans->{due};
518             $trans->desensitize(0);
519         }
520     }
521
522     return $trans;
523 }
524
525 sub renew_all {
526     my ($self, $patron_id, $patron_pwd, $fee_ack) = @_;
527     my ($patron, $item_id);
528     my $trans;
529
530     $trans = C4::SIP::ILS::Transaction::RenewAll->new();
531     if ($fee_ack) {
532         $trans->fee_ack($fee_ack);
533     }
534
535     $trans->patron($patron = C4::SIP::ILS::Patron->new( $patron_id ));
536     if (defined $patron) {
537         siplog("LOG_DEBUG", "ILS::renew_all: patron '%s': renew_ok: %s", $patron->name, $patron->renew_ok);
538     } else {
539         siplog("LOG_DEBUG", "ILS::renew_all: Invalid patron id: '%s'", $patron_id);
540     }
541
542     if (!$patron) {
543                 $trans->screen_msg("Invalid patron barcode.");
544                 return $trans;
545     } elsif (!$patron->renew_ok) {
546                 $trans->screen_msg("Renewals not allowed.");
547                 return $trans;
548     }
549
550         $trans->do_renew_all;
551     $trans->ok(1);
552     return $trans;
553 }
554
555 1;
556 __END__
557