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