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