Bug 10445: make SIP Server respect maxoutstanding system preference
[koha-equinox.git] / C4 / SIP / ILS / Patron.pm
1 #
2 # ILS::Patron.pm
3
4 # A Class for hiding the ILS's concept of the patron from the OpenSIP
5 # system
6 #
7
8 package ILS::Patron;
9
10 use strict;
11 use warnings;
12 use Exporter;
13 use Carp;
14
15 use Sys::Syslog qw(syslog);
16 use Data::Dumper;
17
18 use C4::Debug;
19 use C4::Context;
20 use C4::Koha;
21 use C4::Members;
22 use C4::Reserves;
23 use C4::Branch qw(GetBranchName);
24 use C4::Items qw( GetBarcodeFromItemnumber GetItemnumbersForBiblio);
25 use C4::Auth qw(checkpw_hash);
26
27 our $VERSION = 3.07.00.049;
28
29 our $kp;    # koha patron
30
31 sub new {
32     my ($class, $patron_id) = @_;
33     my $type = ref($class) || $class;
34     my $self;
35     $kp = GetMember(cardnumber=>$patron_id) || GetMember(userid=>$patron_id);
36     $debug and warn "new Patron (GetMember): " . Dumper($kp);
37     unless (defined $kp) {
38         syslog("LOG_DEBUG", "new ILS::Patron(%s): no such patron", $patron_id);
39         return;
40     }
41     $kp = GetMemberDetails($kp->{borrowernumber});
42     $debug and warn "new Patron (GetMemberDetails): " . Dumper($kp);
43     my $pw        = $kp->{password};
44     my $flags     = $kp->{flags};     # or warn "Warning: No flags from patron object for '$patron_id'";
45     my $debarred  = defined($kp->{flags}->{DBARRED});
46     $debug and warn sprintf("Debarred = %s : ", ($debarred||'undef')) . Dumper(%{$kp->{flags}});
47     my ($day, $month, $year) = (localtime)[3,4,5];
48     my $today    = sprintf '%04d-%02d-%02d', $year+1900, $month+1, $day;
49     my $expired  = ($today gt $kp->{dateexpiry}) ? 1 : 0;
50     if ($expired) {
51         if ($kp->{opacnote} ) {
52             $kp->{opacnote} .= q{ };
53         }
54         $kp->{opacnote} .= 'PATRON EXPIRED';
55     }
56     my %ilspatron;
57     my $adr     = _get_address($kp);
58     my $dob     = $kp->{dateofbirth};
59     $dob and $dob =~ s/-//g;    # YYYYMMDD
60     my $dexpiry     = $kp->{dateexpiry};
61     $dexpiry and $dexpiry =~ s/-//g;    # YYYYMMDD
62     my $fines_amount = $flags->{CHARGES}->{amount};
63     $fines_amount = ($fines_amount and $fines_amount > 0) ? $fines_amount : 0;
64     {
65     no warnings;    # any of these $kp->{fields} being concat'd could be undef
66     %ilspatron = (
67         getmemberdetails_object => $kp,
68         name => $kp->{firstname} . " " . $kp->{surname},
69         id   => $kp->{cardnumber},    # to SIP, the id is the BARCODE, not userid
70         password        => $pw,
71         ptype           => $kp->{categorycode},     # 'A'dult.  Whatever.
72         dateexpiry      => $dexpiry,
73         dateexpiry_iso  => $kp->{dateexpiry},
74         birthdate       => $dob,
75         birthdate_iso   => $kp->{dateofbirth},
76         branchcode      => $kp->{branchcode},
77         library_name    => "",                      # only populated if needed, cached here
78         borrowernumber  => $kp->{borrowernumber},
79         address         => $adr,
80         home_phone      => $kp->{phone},
81         email_addr      => $kp->{email},
82         charge_ok       => ( !$debarred && !$expired ),
83         renew_ok        => ( !$debarred && !$expired ),
84         recall_ok       => ( !$debarred && !$expired ),
85         hold_ok         => ( !$debarred && !$expired ),
86         card_lost       => ( $kp->{lost} || $kp->{gonenoaddress} || $flags->{LOST} ),
87         claims_returned => 0,
88         fines           => $fines_amount, # GetMemberAccountRecords($kp->{borrowernumber})
89         fees            => 0,             # currently not distinct from fines
90         recall_overdue  => 0,
91         items_billed    => 0,
92         screen_msg      => 'Greetings from Koha. ' . $kp->{opacnote},
93         print_line      => '',
94         items           => [],
95         hold_items      => $flags->{WAITING}->{itemlist},
96         overdue_items   => $flags->{ODUES}->{itemlist},
97         fine_items      => [],
98         recall_items    => [],
99         unavail_holds   => [],
100         inet            => ( !$debarred && !$expired ),
101         expired         => $expired,
102     );
103     }
104     $debug and warn "patron fines: $ilspatron{fines} ... amountoutstanding: $kp->{amountoutstanding} ... CHARGES->amount: $flags->{CHARGES}->{amount}";
105     for (qw(EXPIRED CHARGES CREDITS GNA LOST DBARRED NOTES)) {
106         ($flags->{$_}) or next;
107         if ($_ ne 'NOTES' and $flags->{$_}->{message}) {
108             $ilspatron{screen_msg} .= " -- " . $flags->{$_}->{message};  # show all but internal NOTES
109         }
110         if ($flags->{$_}->{noissues}) {
111             foreach my $toggle (qw(charge_ok renew_ok recall_ok hold_ok inet)) {
112                 $ilspatron{$toggle} = 0;    # if we get noissues, disable everything
113             }
114         }
115     }
116
117     # FIXME: populate fine_items recall_items
118     $ilspatron{unavail_holds} = _get_outstanding_holds($kp->{borrowernumber});
119     $ilspatron{items} = GetPendingIssues($kp->{borrowernumber});
120     $self = \%ilspatron;
121     $debug and warn Dumper($self);
122     syslog("LOG_DEBUG", "new ILS::Patron(%s): found patron '%s'", $patron_id,$self->{id});
123     bless $self, $type;
124     return $self;
125 }
126
127
128 # 0 means read-only
129 # 1 means read/write
130
131 my %fields = (
132     id                      => 0,
133     name                    => 0,
134     address                 => 0,
135     email_addr              => 0,
136     home_phone              => 0,
137     birthdate               => 0,
138     birthdate_iso           => 0,
139     dateexpiry              => 0,
140     dateexpiry_iso          => 0,
141     ptype                   => 0,
142     charge_ok               => 0,   # for patron_status[0] (inverted)
143     renew_ok                => 0,   # for patron_status[1] (inverted)
144     recall_ok               => 0,   # for patron_status[2] (inverted)
145     hold_ok                 => 0,   # for patron_status[3] (inverted)
146     card_lost               => 0,   # for patron_status[4]
147     recall_overdue          => 0,
148     currency                => 1,
149 #   fee_limit               => 0,
150     screen_msg              => 1,
151     print_line              => 1,
152     too_many_charged        => 0,   # for patron_status[5]
153     too_many_overdue        => 0,   # for patron_status[6]
154     too_many_renewal        => 0,   # for patron_status[7]
155     too_many_claim_return   => 0,   # for patron_status[8]
156     too_many_lost           => 0,   # for patron_status[9]
157 #   excessive_fines         => 0,   # for patron_status[10]
158 #   excessive_fees          => 0,   # for patron_status[11]
159     recall_overdue          => 0,   # for patron_status[12]
160     too_many_billed         => 0,   # for patron_status[13]
161     inet                    => 0,   # EnvisionWare extension
162     getmemberdetails_object => 0,
163 );
164
165 our $AUTOLOAD;
166
167 sub DESTROY {
168     # be cool.  needed for AUTOLOAD(?)
169 }
170
171 sub AUTOLOAD {
172     my $self = shift;
173     my $class = ref($self) or croak "$self is not an object";
174     my $name = $AUTOLOAD;
175
176     $name =~ s/.*://;
177
178     unless (exists $fields{$name}) {
179         croak "Cannot access '$name' field of class '$class'";
180     }
181
182     if (@_) {
183         $fields{$name} or croak "Field '$name' of class '$class' is READ ONLY.";
184         return $self->{$name} = shift;
185     } else {
186         return $self->{$name};
187     }
188 }
189
190 sub check_password {
191     my ($self, $pwd) = @_;
192     defined $pwd or return 0;                  # you gotta give me something (at least ''), or no deal
193
194     my $hashed_pwd = $self->{password};
195     defined $hashed_pwd or return $pwd eq '';  # if the record has a NULL password, accept '' as match
196
197     # warn sprintf "check_password for %s: '%s' vs. '%s'",($self->{name}||''),($self->{password}||''),($pwd||'');
198     return checkpw_hash($pwd, $hashed_pwd);
199 }
200
201 # A few special cases, not in AUTOLOADed %fields
202 sub fee_amount {
203     my $self = shift;
204     if ( $self->{fines} ) {
205         return $self->{fines};
206     }
207     return;
208 }
209
210 sub fines_amount {
211     my $self = shift;
212     return $self->fee_amount;
213 }
214
215 sub language {
216     my $self = shift;
217     return $self->{language} || '000'; # Unspecified
218 }
219
220 sub expired {
221     my $self = shift;
222     return $self->{expired};
223 }
224
225 #
226 # remove the hold on item item_id from my hold queue.
227 # return true if I was holding the item, false otherwise.
228
229 sub drop_hold {
230     my ($self, $item_id) = @_;
231     return if !$item_id;
232     my $result = 0;
233     foreach (qw(hold_items unavail_holds)) {
234         $self->{$_} or next;
235         for (my $i = 0; $i < scalar @{$self->{$_}}; $i++) {
236             my $held_item = $self->{$_}[$i]->{item_id} or next;
237             if ($held_item eq $item_id) {
238                 splice @{$self->{$_}}, $i, 1;
239                 $result++;
240             }
241         }
242     }
243     return $result;
244 }
245
246 # Accessor method for array_ref values, designed to get the "start" and "end" values
247 # from the SIP request.  Note those incoming values are 1-indexed, not 0-indexed.
248 #
249 sub x_items {
250     my $self      = shift;
251     my $array_var = shift or return;
252     my ($start, $end) = @_;
253
254     my $item_list = [];
255     if ($self->{$array_var}) {
256         if ($start && $start > 1) {
257             --$start;
258         }
259         else {
260             $start = 0;
261         }
262         if ( $end && $end < @{$self->{$array_var}} ) {
263         }
264         else {
265             $end = @{$self->{$array_var}};
266             --$end;
267         }
268         @{$item_list} = @{$self->{$array_var}}[ $start .. $end ];
269
270     }
271     return $item_list;
272 }
273
274 #
275 # List of outstanding holds placed
276 #
277 sub hold_items {
278     my $self = shift;
279     my $item_arr = $self->x_items('hold_items', @_);
280     foreach my $item (@{$item_arr}) {
281         $item->{barcode} = GetBarcodeFromItemnumber($item->{itemnumber});
282     }
283     return $item_arr;
284 }
285
286 sub overdue_items {
287     my $self = shift;
288     return $self->x_items('overdue_items', @_);
289 }
290 sub charged_items {
291     my $self = shift;
292     return $self->x_items('items', @_);
293 }
294 sub fine_items {
295     my $self = shift;
296     return $self->x_items('fine_items', @_);
297 }
298 sub recall_items {
299     my $self = shift;
300     return $self->x_items('recall_items', @_);
301 }
302 sub unavail_holds {
303     my $self = shift;
304     return $self->x_items('unavail_holds', @_);
305 }
306
307 sub block {
308     my ($self, $card_retained, $blocked_card_msg) = @_;
309     foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') {
310         $self->{$field} = 0;
311     }
312     $self->{screen_msg} = "Block feature not implemented";  # $blocked_card_msg || "Card Blocked.  Please contact library staff";
313     # TODO: not really affecting patron record
314     return $self;
315 }
316
317 sub enable {
318     my $self = shift;
319     foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') {
320         $self->{$field} = 1;
321     }
322     syslog("LOG_DEBUG", "Patron(%s)->enable: charge: %s, renew:%s, recall:%s, hold:%s",
323        $self->{id}, $self->{charge_ok}, $self->{renew_ok},
324        $self->{recall_ok}, $self->{hold_ok});
325     $self->{screen_msg} = "Enable feature not implemented."; # "All privileges restored.";   # TODO: not really affecting patron record
326     return $self;
327 }
328
329 sub inet_privileges {
330     my $self = shift;
331     return $self->{inet} ? 'Y' : 'N';
332 }
333
334 sub fee_limit {
335     my $self = shift;
336     return C4::Context->preference("noissuescharge") || 5;
337 }
338
339 sub excessive_fees {
340     my $self = shift;
341     return ($self->fee_amount and $self->fee_amount > $self->fee_limit);
342 }
343
344 sub excessive_fines {
345     my $self = shift;
346     return $self->excessive_fees;   # excessive_fines is the same thing as excessive_fees for Koha
347 }
348
349 sub holds_blocked_by_excessive_fees {
350     return ( $self->fee_amount
351           && $self->fee_amount > C4::Context->preference("maxoutstanding") );
352 }
353     
354 sub library_name {
355     my $self = shift;
356     unless ($self->{library_name}) {
357         $self->{library_name} = GetBranchName($self->{branchcode});
358     }
359     return $self->{library_name};
360 }
361 #
362 # Messages
363 #
364
365 sub invalid_patron {
366     my $self = shift;
367     return "Please contact library staff";
368 }
369
370 sub charge_denied {
371     my $self = shift;
372     return "Please contact library staff";
373 }
374
375 sub _get_address {
376     my $patron = shift;
377
378     my $address = $patron->{streetnumber} || q{};
379     for my $field (qw( roaddetails address address2 city state zipcode country))
380     {
381         next unless $patron->{$field};
382         if ($address) {
383             $address .= q{ };
384             $address .= $patron->{$field};
385         }
386         else {
387             $address .= $patron->{$field};
388         }
389     }
390     return $address;
391 }
392
393 sub _get_outstanding_holds {
394     my $borrowernumber = shift;
395     my @hold_array = grep { !defined $_->{found} || $_->{found} ne 'W'} GetReservesFromBorrowernumber($borrowernumber);
396     foreach my $h (@hold_array) {
397         my $item;
398         if ($h->{itemnumber}) {
399             $item = $h->{itemnumber};
400         }
401         else {
402             # We need to return a barcode for the biblio so the client
403             # can request the biblio info
404             $item = ( GetItemnumbersForBiblio($h->{biblionumber}) )[0];
405         }
406         $h->{barcode} = GetBarcodeFromItemnumber($item);
407     }
408     return \@hold_array;
409 }
410
411 1;
412 __END__
413
414 =head1 EXAMPLES
415
416   our %patron_example = (
417           djfiander => {
418               name => "David J. Fiander",
419               id => 'djfiander',
420               password => '6789',
421               ptype => 'A', # 'A'dult.  Whatever.
422               birthdate => '19640925',
423               address => '2 Meadowvale Dr. St Thomas, ON',
424               home_phone => '(519) 555 1234',
425               email_addr => 'djfiander@hotmail.com',
426               charge_ok => 1,
427               renew_ok => 1,
428               recall_ok => 0,
429               hold_ok => 1,
430               card_lost => 0,
431               claims_returned => 0,
432               fines => 100,
433               fees => 0,
434               recall_overdue => 0,
435               items_billed => 0,
436               screen_msg => '',
437               print_line => '',
438               items => [],
439               hold_items => [],
440               overdue_items => [],
441               fine_items => ['Computer Time'],
442               recall_items => [],
443               unavail_holds => [],
444               inet => 1,
445           },
446   );
447
448  From borrowers table:
449 +---------------------+--------------+------+-----+---------+----------------+
450 | Field               | Type         | Null | Key | Default | Extra          |
451 +---------------------+--------------+------+-----+---------+----------------+
452 | borrowernumber      | int(11)      | NO   | PRI | NULL    | auto_increment |
453 | cardnumber          | varchar(16)  | YES  | UNI | NULL    |                |
454 | surname             | mediumtext   | NO   |     | NULL    |                |
455 | firstname           | text         | YES  |     | NULL    |                |
456 | title               | mediumtext   | YES  |     | NULL    |                |
457 | othernames          | mediumtext   | YES  |     | NULL    |                |
458 | initials            | text         | YES  |     | NULL    |                |
459 | streetnumber        | varchar(10)  | YES  |     | NULL    |                |
460 | streettype          | varchar(50)  | YES  |     | NULL    |                |
461 | address             | mediumtext   | NO   |     | NULL    |                |
462 | address2            | text         | YES  |     | NULL    |                |
463 | city                | mediumtext   | NO   |     | NULL    |                |
464 | state               | mediumtext   | YES  |     | NULL    |                |
465 | zipcode             | varchar(25)  | YES  |     | NULL    |                |
466 | country             | text         | YES  |     | NULL    |                |
467 | email               | mediumtext   | YES  |     | NULL    |                |
468 | phone               | text         | YES  |     | NULL    |                |
469 | mobile              | varchar(50)  | YES  |     | NULL    |                |
470 | fax                 | mediumtext   | YES  |     | NULL    |                |
471 | emailpro            | text         | YES  |     | NULL    |                |
472 | phonepro            | text         | YES  |     | NULL    |                |
473 | B_streetnumber      | varchar(10)  | YES  |     | NULL    |                |
474 | B_streettype        | varchar(50)  | YES  |     | NULL    |                |
475 | B_address           | varchar(100) | YES  |     | NULL    |                |
476 | B_address2          | text         | YES  |     | NULL    |                |
477 | B_city              | mediumtext   | YES  |     | NULL    |                |
478 | B_state             | mediumtext   | YES  |     | NULL    |                |
479 | B_zipcode           | varchar(25)  | YES  |     | NULL    |                |
480 | B_country           | text         | YES  |     | NULL    |                |
481 | B_email             | text         | YES  |     | NULL    |                |
482 | B_phone             | mediumtext   | YES  |     | NULL    |                |
483 | dateofbirth         | date         | YES  |     | NULL    |                |
484 | branchcode          | varchar(10)  | NO   | MUL |         |                |
485 | categorycode        | varchar(10)  | NO   | MUL |         |                |
486 | dateenrolled        | date         | YES  |     | NULL    |                |
487 | dateexpiry          | date         | YES  |     | NULL    |                |
488 | gonenoaddress       | tinyint(1)   | YES  |     | NULL    |                |
489 | lost                | tinyint(1)   | YES  |     | NULL    |                |
490 | debarred            | tinyint(1)   | YES  |     | NULL    |                |
491 | contactname         | mediumtext   | YES  |     | NULL    |                |
492 | contactfirstname    | text         | YES  |     | NULL    |                |
493 | contacttitle        | text         | YES  |     | NULL    |                |
494 | guarantorid         | int(11)      | YES  | MUL | NULL    |                |
495 | borrowernotes       | mediumtext   | YES  |     | NULL    |                |
496 | relationship        | varchar(100) | YES  |     | NULL    |                |
497 | ethnicity           | varchar(50)  | YES  |     | NULL    |                |
498 | ethnotes            | varchar(255) | YES  |     | NULL    |                |
499 | sex                 | varchar(1)   | YES  |     | NULL    |                |
500 | password            | varchar(30)  | YES  |     | NULL    |                |
501 | flags               | int(11)      | YES  |     | NULL    |                |
502 | userid              | varchar(30)  | YES  | MUL | NULL    |                |
503 | opacnote            | mediumtext   | YES  |     | NULL    |                |
504 | contactnote         | varchar(255) | YES  |     | NULL    |                |
505 | sort1               | varchar(80)  | YES  |     | NULL    |                |
506 | sort2               | varchar(80)  | YES  |     | NULL    |                |
507 | altcontactfirstname | varchar(255) | YES  |     | NULL    |                |
508 | altcontactsurname   | varchar(255) | YES  |     | NULL    |                |
509 | altcontactaddress1  | varchar(255) | YES  |     | NULL    |                |
510 | altcontactaddress2  | varchar(255) | YES  |     | NULL    |                |
511 | altcontactaddress3  | varchar(255) | YES  |     | NULL    |                |
512 | altcontactstate     | mediumtext   | YES  |     | NULL    |                |
513 | altcontactzipcode   | varchar(50)  | YES  |     | NULL    |                |
514 | altcontactcountry   | text         | YES  |     | NULL    |                |
515 | altcontactphone     | varchar(50)  | YES  |     | NULL    |                |
516 | smsalertnumber      | varchar(50)  | YES  |     | NULL    |                |
517 | privacy             | int(11)      | NO   |     | 1       |                |
518 +---------------------+--------------+------+-----+---------+----------------+
519
520
521  From C4::Members
522
523  $flags->{KEY}
524  {CHARGES}
525     {message}     Message showing patron's credit or debt
526     {noissues}    Set if patron owes >$5.00
527  {GNA}             Set if patron gone w/o address
528     {message}     "Borrower has no valid address"
529     {noissues}    Set.
530  {LOST}            Set if patron's card reported lost
531     {message}     Message to this effect
532     {noissues}    Set.
533  {DBARRED}         Set if patron is debarred
534     {message}     Message to this effect
535     {noissues}    Set.
536  {NOTES}           Set if patron has notes
537     {message}     Notes about patron
538  {ODUES}           Set if patron has overdue books
539     {message}     "Yes"
540     {itemlist}    ref-to-array: list of overdue books
541     {itemlisttext}    Text list of overdue items
542  {WAITING}         Set if there are items available that the patron reserved
543     {message}     Message to this effect
544     {itemlist}    ref-to-array: list of available items
545
546 =cut
547