Bug 19382: (QA follow-up) Fix typos
[koha.git] / C4 / SIP / ILS / Patron.pm
blob9820013ee71b11cc5178e3a7efa346fd4303e0b7
2 # ILS::Patron.pm
3 #
4 # A Class for hiding the ILS's concept of the patron from the OpenSIP
5 # system
8 package C4::SIP::ILS::Patron;
10 use strict;
11 use warnings;
12 use Exporter;
13 use Carp;
15 use C4::SIP::Sip qw(siplog);
16 use Data::Dumper;
18 use C4::SIP::Sip qw(add_field maybe_add);
20 use C4::Debug;
21 use C4::Context;
22 use C4::Koha;
23 use C4::Members;
24 use C4::Reserves;
25 use C4::Auth qw(checkpw);
27 use Koha::Items;
28 use Koha::Libraries;
29 use Koha::Patrons;
31 our $kp; # koha patron
33 =head1 Methods
35 =cut
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 siplog("LOG_DEBUG", "new ILS::Patron(%s): no such patron", $patron_id);
46 return;
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{ };
60 $kp->{opacnote} .= 'PATRON EXPIRED';
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
69 # Get fines and add fines for guarantees (depends on preference NoIssuesChargeGuarantees)
70 my $fines_amount = $flags->{CHARGES}->{amount}; #TODO Replace with $patron->account->non_issues_charges
71 $fines_amount = ($fines_amount and $fines_amount > 0) ? $fines_amount : 0;
72 if ( C4::Context->preference('NoIssuesChargeGuarantorsWithGuarantees') ) {
73 $fines_amount += $patron->relationships_debt({ include_guarantors => 1, only_this_guarantor => 0, include_this_patron => 1 });
74 } else {
75 my $guarantees_fines_amount = $flags->{CHARGES_GUARANTEES} ? $flags->{CHARGES_GUARANTEES}->{amount} : 0; #TODO: Replace with $patron->relationships_debt
76 $fines_amount += $guarantees_fines_amount;
79 my $fee_limit = _fee_limit();
80 my $fine_blocked = $fines_amount > $fee_limit;
81 my $circ_blocked =( C4::Context->preference('OverduesBlockCirc') ne "noblock" && defined $flags->{ODUES}->{itemlist} ) ? 1 : 0;
83 no warnings; # any of these $kp->{fields} being concat'd could be undef
84 %ilspatron = (
85 name => $kp->{firstname} . " " . $kp->{surname},
86 id => $kp->{cardnumber}, # to SIP, the id is the BARCODE, not userid
87 password => $pw,
88 ptype => $kp->{categorycode}, # 'A'dult. Whatever.
89 dateexpiry => $dexpiry,
90 dateexpiry_iso => $kp->{dateexpiry},
91 birthdate => $dob,
92 birthdate_iso => $kp->{dateofbirth},
93 branchcode => $kp->{branchcode},
94 library_name => "", # only populated if needed, cached here
95 borrowernumber => $kp->{borrowernumber},
96 address => $adr,
97 home_phone => $kp->{phone},
98 email_addr => $kp->{email},
99 charge_ok => ( !$debarred && !$expired && !$fine_blocked && !$circ_blocked),
100 renew_ok => ( !$debarred && !$expired && !$fine_blocked),
101 recall_ok => ( !$debarred && !$expired && !$fine_blocked),
102 hold_ok => ( !$debarred && !$expired && !$fine_blocked),
103 card_lost => ( $kp->{lost} || $kp->{gonenoaddress} || $flags->{LOST} ),
104 claims_returned => 0,
105 fines => $fines_amount,
106 fees => 0, # currently not distinct from fines
107 recall_overdue => 0,
108 items_billed => 0,
109 screen_msg => 'Greetings from Koha. ' . $kp->{opacnote},
110 print_line => '',
111 items => [],
112 hold_items => $flags->{WAITING}->{itemlist},
113 overdue_items => $flags->{ODUES}->{itemlist},
114 too_many_overdue => $circ_blocked,
115 fine_items => [],
116 recall_items => [],
117 unavail_holds => [],
118 inet => ( !$debarred && !$expired ),
119 expired => $expired,
120 fee_limit => $fee_limit,
121 userid => $kp->{userid},
124 $debug and warn "patron fines: $ilspatron{fines} ... amountoutstanding: $kp->{amountoutstanding} ... CHARGES->amount: $flags->{CHARGES}->{amount}";
126 if ( $patron->is_debarred and $patron->debarredcomment ) {
127 $ilspatron{screen_msg} .= " -- " . $patron->debarredcomment;
129 if ( $circ_blocked ) {
130 $ilspatron{screen_msg} .= " -- " . "Patron has overdues";
132 for (qw(EXPIRED CHARGES CREDITS GNA LOST NOTES)) {
133 ($flags->{$_}) or next;
134 if ($_ ne 'NOTES' and $flags->{$_}->{message}) {
135 $ilspatron{screen_msg} .= " -- " . $flags->{$_}->{message}; # show all but internal NOTES
137 if ($flags->{$_}->{noissues}) {
138 foreach my $toggle (qw(charge_ok renew_ok recall_ok hold_ok inet)) {
139 $ilspatron{$toggle} = 0; # if we get noissues, disable everything
144 # FIXME: populate fine_items recall_items
145 $ilspatron{unavail_holds} = _get_outstanding_holds($kp->{borrowernumber});
147 my $pending_checkouts = $patron->pending_checkouts;
148 my @barcodes;
149 while ( my $c = $pending_checkouts->next ) {
150 push @barcodes, { barcode => $c->item->barcode };
152 $ilspatron{items} = \@barcodes;
154 $self = \%ilspatron;
155 $debug and warn Dumper($self);
156 siplog("LOG_DEBUG", "new ILS::Patron(%s): found patron '%s'", $patron_id,$self->{id});
157 bless $self, $type;
158 return $self;
162 # 0 means read-only
163 # 1 means read/write
165 my %fields = (
166 id => 0,
167 borrowernumber => 0,
168 name => 0,
169 address => 0,
170 email_addr => 0,
171 home_phone => 0,
172 birthdate => 0,
173 birthdate_iso => 0,
174 dateexpiry => 0,
175 dateexpiry_iso => 0,
176 ptype => 0,
177 charge_ok => 0, # for patron_status[0] (inverted)
178 renew_ok => 0, # for patron_status[1] (inverted)
179 recall_ok => 0, # for patron_status[2] (inverted)
180 hold_ok => 0, # for patron_status[3] (inverted)
181 card_lost => 0, # for patron_status[4]
182 recall_overdue => 0,
183 currency => 1,
184 fee_limit => 0,
185 screen_msg => 1,
186 print_line => 1,
187 too_many_charged => 0, # for patron_status[5]
188 too_many_overdue => 0, # for patron_status[6]
189 too_many_renewal => 0, # for patron_status[7]
190 too_many_claim_return => 0, # for patron_status[8]
191 too_many_lost => 0, # for patron_status[9]
192 # excessive_fines => 0, # for patron_status[10]
193 # excessive_fees => 0, # for patron_status[11]
194 recall_overdue => 0, # for patron_status[12]
195 too_many_billed => 0, # for patron_status[13]
196 inet => 0, # EnvisionWare extension
199 our $AUTOLOAD;
201 sub DESTROY {
202 # be cool. needed for AUTOLOAD(?)
205 sub AUTOLOAD {
206 my $self = shift;
207 my $class = ref($self) or croak "$self is not an object";
208 my $name = $AUTOLOAD;
210 $name =~ s/.*://;
212 unless (exists $fields{$name}) {
213 croak "Cannot access '$name' field of class '$class'";
216 if (@_) {
217 $fields{$name} or croak "Field '$name' of class '$class' is READ ONLY.";
218 return $self->{$name} = shift;
219 } else {
220 return $self->{$name};
224 =head2 format
226 This method uses a template to build a string from a Koha::Patron object
227 If errors are encountered in processing template we log them and return nothing
229 =cut
231 sub format {
232 my ( $self, $template ) = @_;
234 if ($template) {
235 require Template;
236 require Koha::Patrons;
238 my $tt = Template->new();
240 my $patron = Koha::Patrons->find( $self->{borrowernumber} );
242 my $output;
243 eval {
244 $tt->process( \$template, { patron => $patron }, \$output );
246 if ( $@ ){
247 siplog("LOG_DEBUG", "Error processing template: $template");
248 return "";
250 return $output;
254 sub check_password {
255 my ( $self, $pwd ) = @_;
257 # you gotta give me something (at least ''), or no deal
258 return 0 unless defined $pwd;
260 # If the record has a NULL password, accept '' as match
261 return $pwd eq q{} unless $self->{password};
263 my $dbh = C4::Context->dbh;
264 my $ret = 0;
265 ($ret) = checkpw( $dbh, $self->{userid}, $pwd, undef, undef, 1 ); # dbh, userid, query, type, no_set_userenv
266 return $ret;
269 # A few special cases, not in AUTOLOADed %fields
270 sub fee_amount {
271 my $self = shift;
272 if ( $self->{fines} ) {
273 return $self->{fines};
275 return 0;
278 sub fines_amount {
279 my $self = shift;
280 return $self->fee_amount;
283 sub language {
284 my $self = shift;
285 return $self->{language} || '000'; # Unspecified
288 sub expired {
289 my $self = shift;
290 return $self->{expired};
294 # remove the hold on item item_id from my hold queue.
295 # return true if I was holding the item, false otherwise.
297 sub drop_hold {
298 my ($self, $item_id) = @_;
299 return if !$item_id;
300 my $result = 0;
301 foreach (qw(hold_items unavail_holds)) {
302 $self->{$_} or next;
303 for (my $i = 0; $i < scalar @{$self->{$_}}; $i++) {
304 my $held_item = $self->{$_}[$i]->{barcode} or next;
305 if ($held_item eq $item_id) {
306 splice @{$self->{$_}}, $i, 1;
307 $result++;
311 return $result;
314 # Accessor method for array_ref values, designed to get the "start" and "end" values
315 # from the SIP request. Note those incoming values are 1-indexed, not 0-indexed.
317 sub x_items {
318 my $self = shift;
319 my $array_var = shift or return;
320 my ($start, $end) = @_;
322 my $item_list = [];
323 if ($self->{$array_var}) {
324 if ($start && $start > 1) {
325 --$start;
327 else {
328 $start = 0;
330 if ( $end && $end < @{$self->{$array_var}} ) {
332 else {
333 $end = @{$self->{$array_var}};
334 --$end;
336 @{$item_list} = @{$self->{$array_var}}[ $start .. $end ];
339 return $item_list;
343 # List of outstanding holds placed
345 sub hold_items {
346 my $self = shift;
347 my $item_arr = $self->x_items('hold_items', @_);
348 foreach my $item (@{$item_arr}) {
349 my $item_obj = Koha::Items->find($item->{itemnumber});
350 $item->{barcode} = $item_obj ? $item_obj->barcode : undef;
352 return $item_arr;
355 sub overdue_items {
356 my $self = shift;
357 return $self->x_items('overdue_items', @_);
359 sub charged_items {
360 my $self = shift;
361 return $self->x_items('items', @_);
363 sub fine_items {
364 require Koha::Database;
365 require Template;
367 my $self = shift;
368 my $start = shift;
369 my $end = shift;
370 my $server = shift;
372 my @fees = Koha::Database->new()->schema()->resultset('Accountline')->search(
374 borrowernumber => $self->{borrowernumber},
375 amountoutstanding => { '>' => '0' },
379 $start = $start ? $start - 1 : 0;
380 $end = $end ? $end : scalar @fees - 1;
382 my $av_field_template = $server ? $server->{account}->{av_field_template} : undef;
383 $av_field_template ||= "[% accountline.description %] [% accountline.amountoutstanding | format('%.2f') %]";
385 my $tt = Template->new();
387 my @return_values;
388 for ( my $i = $start; $i <= $end; $i++ ) {
389 my $fee = $fees[$i];
391 my $output;
392 $tt->process( \$av_field_template, { accountline => $fee }, \$output );
393 push( @return_values, { barcode => $output } );
396 return \@return_values;
398 sub recall_items {
399 my $self = shift;
400 return $self->x_items('recall_items', @_);
402 sub unavail_holds {
403 my $self = shift;
404 return $self->x_items('unavail_holds', @_);
407 sub block {
408 my ($self, $card_retained, $blocked_card_msg) = @_;
409 foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') {
410 $self->{$field} = 0;
412 $self->{screen_msg} = "Block feature not implemented"; # $blocked_card_msg || "Card Blocked. Please contact library staff";
413 # TODO: not really affecting patron record
414 return $self;
417 sub enable {
418 my $self = shift;
419 foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') {
420 $self->{$field} = 1;
422 siplog("LOG_DEBUG", "Patron(%s)->enable: charge: %s, renew:%s, recall:%s, hold:%s",
423 $self->{id}, $self->{charge_ok}, $self->{renew_ok},
424 $self->{recall_ok}, $self->{hold_ok});
425 $self->{screen_msg} = "Enable feature not implemented."; # "All privileges restored."; # TODO: not really affecting patron record
426 return $self;
429 sub inet_privileges {
430 my $self = shift;
431 return $self->{inet} ? 'Y' : 'N';
434 sub _fee_limit {
435 return C4::Context->preference('noissuescharge') || 5;
438 sub excessive_fees {
439 my $self = shift;
440 return ($self->fee_amount and $self->fee_amount > $self->fee_limit);
443 sub excessive_fines {
444 my $self = shift;
445 return $self->excessive_fees; # excessive_fines is the same thing as excessive_fees for Koha
448 sub holds_blocked_by_excessive_fees {
449 my $self = shift;
450 return ( $self->fee_amount
451 && $self->fee_amount > C4::Context->preference("maxoutstanding") );
454 sub library_name {
455 my $self = shift;
456 unless ($self->{library_name}) {
457 my $library = Koha::Libraries->find( $self->{branchcode} );
458 $self->{library_name} = $library ? $library->branchname : '';
460 return $self->{library_name};
463 # Messages
466 sub invalid_patron {
467 my $self = shift;
468 return "Please contact library staff";
471 sub charge_denied {
472 my $self = shift;
473 return "Please contact library staff";
476 =head2 update_lastseen
478 $patron->update_lastseen();
480 Patron method to update lastseen field in borrower
481 to record that patron has been seen via sip connection
483 =cut
485 sub update_lastseen {
486 my $self = shift;
487 my $kohaobj = Koha::Patrons->find( $self->{borrowernumber} );
488 $kohaobj->track_login if $kohaobj; # track_login checks the pref
491 sub _get_address {
492 my $patron = shift;
494 my $address = $patron->{streetnumber} || q{};
495 for my $field (qw( roaddetails address address2 city state zipcode country))
497 next unless $patron->{$field};
498 if ($address) {
499 $address .= q{ };
500 $address .= $patron->{$field};
502 else {
503 $address .= $patron->{$field};
506 return $address;
509 sub _get_outstanding_holds {
510 my $borrowernumber = shift;
512 my $patron = Koha::Patrons->find( $borrowernumber );
513 my $holds = $patron->holds->search( { -or => [ { found => undef }, { found => { '!=' => 'W' } } ] } );
514 my @holds;
515 while ( my $hold = $holds->next ) {
516 my $item;
517 if ($hold->itemnumber) {
518 $item = $hold->item;
520 else {
521 # We need to return a barcode for the biblio so the client
522 # can request the biblio info
523 my $items = $hold->biblio->items;
524 $item = $items->count ? $items->next : undef;
526 my $unblessed_hold = $hold->unblessed;
528 $unblessed_hold->{barcode} = $item ? $item->barcode : undef;
530 push @holds, $unblessed_hold;
532 return \@holds;
535 =head2 build_patron_attributes_string
537 This method builds the part of the sip message for extended patron
538 attributes as defined in the sip config
540 =cut
542 sub build_patron_attributes_string {
543 my ( $self, $server ) = @_;
545 my $string = q{};
546 if ( $server->{account}->{patron_attribute} ) {
547 my @attributes_to_send =
548 ref $server->{account}->{patron_attribute} eq "ARRAY"
549 ? @{ $server->{account}->{patron_attribute} }
550 : ( $server->{account}->{patron_attribute} );
552 foreach my $a ( @attributes_to_send ) {
553 my @attributes = Koha::Patron::Attributes->search(
555 borrowernumber => $self->{borrowernumber},
556 code => $a->{code}
560 foreach my $attribute ( @attributes ) {
561 my $value = $attribute->attribute();
562 $string .= add_field( $a->{field}, $value );
567 return $string;
571 =head2 build_custom_field_string
573 This method builds the part of the sip message for custom patron fields as defined in the sip config
575 =cut
577 sub build_custom_field_string {
578 my ( $self, $server ) = @_;
580 my $string = q{};
582 if ( $server->{account}->{custom_patron_field} ) {
583 my @custom_fields =
584 ref $server->{account}->{custom_patron_field} eq "ARRAY"
585 ? @{ $server->{account}->{custom_patron_field} }
586 : $server->{account}->{custom_patron_field};
587 foreach my $custom_field ( @custom_fields ) {
588 $string .= maybe_add( $custom_field->{field}, $self->format( $custom_field->{template} ) ) if defined $custom_field->{field};
591 return $string;
595 __END__
597 =head1 EXAMPLES
599 our %patron_example = (
600 djfiander => {
601 name => "David J. Fiander",
602 id => 'djfiander',
603 password => '6789',
604 ptype => 'A', # 'A'dult. Whatever.
605 birthdate => '19640925',
606 address => '2 Meadowvale Dr. St Thomas, ON',
607 home_phone => '(519) 555 1234',
608 email_addr => 'djfiander@hotmail.com',
609 charge_ok => 1,
610 renew_ok => 1,
611 recall_ok => 0,
612 hold_ok => 1,
613 card_lost => 0,
614 claims_returned => 0,
615 fines => 100,
616 fees => 0,
617 recall_overdue => 0,
618 items_billed => 0,
619 screen_msg => '',
620 print_line => '',
621 items => [],
622 hold_items => [],
623 overdue_items => [],
624 fine_items => ['Computer Time'],
625 recall_items => [],
626 unavail_holds => [],
627 inet => 1,
631 From borrowers table:
632 +---------------------+--------------+------+-----+---------+----------------+
633 | Field | Type | Null | Key | Default | Extra |
634 +---------------------+--------------+------+-----+---------+----------------+
635 | borrowernumber | int(11) | NO | PRI | NULL | auto_increment |
636 | cardnumber | varchar(16) | YES | UNI | NULL | |
637 | surname | mediumtext | NO | | NULL | |
638 | firstname | text | YES | | NULL | |
639 | title | mediumtext | YES | | NULL | |
640 | othernames | mediumtext | YES | | NULL | |
641 | initials | text | YES | | NULL | |
642 | streetnumber | varchar(10) | YES | | NULL | |
643 | streettype | varchar(50) | YES | | NULL | |
644 | address | mediumtext | NO | | NULL | |
645 | address2 | text | YES | | NULL | |
646 | city | mediumtext | NO | | NULL | |
647 | state | mediumtext | YES | | NULL | |
648 | zipcode | varchar(25) | YES | | NULL | |
649 | country | text | YES | | NULL | |
650 | email | mediumtext | YES | | NULL | |
651 | phone | text | YES | | NULL | |
652 | mobile | varchar(50) | YES | | NULL | |
653 | fax | mediumtext | YES | | NULL | |
654 | emailpro | text | YES | | NULL | |
655 | phonepro | text | YES | | NULL | |
656 | B_streetnumber | varchar(10) | YES | | NULL | |
657 | B_streettype | varchar(50) | YES | | NULL | |
658 | B_address | varchar(100) | YES | | NULL | |
659 | B_address2 | text | YES | | NULL | |
660 | B_city | mediumtext | YES | | NULL | |
661 | B_state | mediumtext | YES | | NULL | |
662 | B_zipcode | varchar(25) | YES | | NULL | |
663 | B_country | text | YES | | NULL | |
664 | B_email | text | YES | | NULL | |
665 | B_phone | mediumtext | YES | | NULL | |
666 | dateofbirth | date | YES | | NULL | |
667 | branchcode | varchar(10) | NO | MUL | | |
668 | categorycode | varchar(10) | NO | MUL | | |
669 | dateenrolled | date | YES | | NULL | |
670 | dateexpiry | date | YES | | NULL | |
671 | gonenoaddress | tinyint(1) | YES | | NULL | |
672 | lost | tinyint(1) | YES | | NULL | |
673 | debarred | tinyint(1) | YES | | NULL | |
674 | contactname | mediumtext | YES | | NULL | |
675 | contactfirstname | text | YES | | NULL | |
676 | contacttitle | text | YES | | NULL | |
677 | borrowernotes | mediumtext | YES | | NULL | |
678 | relationship | varchar(100) | YES | | NULL | |
679 | ethnicity | varchar(50) | YES | | NULL | |
680 | ethnotes | varchar(255) | YES | | NULL | |
681 | sex | varchar(1) | YES | | NULL | |
682 | password | varchar(30) | YES | | NULL | |
683 | flags | int(11) | YES | | NULL | |
684 | userid | varchar(30) | YES | MUL | NULL | |
685 | opacnote | mediumtext | YES | | NULL | |
686 | contactnote | varchar(255) | YES | | NULL | |
687 | sort1 | varchar(80) | YES | | NULL | |
688 | sort2 | varchar(80) | YES | | NULL | |
689 | altcontactfirstname | varchar(255) | YES | | NULL | |
690 | altcontactsurname | varchar(255) | YES | | NULL | |
691 | altcontactaddress1 | varchar(255) | YES | | NULL | |
692 | altcontactaddress2 | varchar(255) | YES | | NULL | |
693 | altcontactaddress3 | varchar(255) | YES | | NULL | |
694 | altcontactstate | mediumtext | YES | | NULL | |
695 | altcontactzipcode | varchar(50) | YES | | NULL | |
696 | altcontactcountry | text | YES | | NULL | |
697 | altcontactphone | varchar(50) | YES | | NULL | |
698 | smsalertnumber | varchar(50) | YES | | NULL | |
699 | privacy | int(11) | NO | | 1 | |
700 +---------------------+--------------+------+-----+---------+----------------+
703 From C4::Members
705 $flags->{KEY}
706 {CHARGES}
707 {message} Message showing patron's credit or debt
708 {noissues} Set if patron owes >$5.00
709 {GNA} Set if patron gone w/o address
710 {message} "Borrower has no valid address"
711 {noissues} Set.
712 {LOST} Set if patron's card reported lost
713 {message} Message to this effect
714 {noissues} Set.
715 {DBARRED} Set if patron is debarred
716 {message} Message to this effect
717 {noissues} Set.
718 {NOTES} Set if patron has notes
719 {message} Notes about patron
720 {ODUES} Set if patron has overdue books
721 {message} "Yes"
722 {itemlist} ref-to-array: list of overdue books
723 {itemlisttext} Text list of overdue items
724 {WAITING} Set if there are items available that the patron reserved
725 {message} Message to this effect
726 {itemlist} ref-to-array: list of available items
728 =cut