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