Bug 20816: Add ability to define custom templated fields in SIP patron responses
[koha.git] / C4 / SIP / ILS / Patron.pm
blobb528501f39d81bb83e389c845f39d736547e9578
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 Sys::Syslog qw(syslog);
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 syslog("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};
71 $fines_amount = ($fines_amount and $fines_amount > 0) ? $fines_amount : 0;
72 my $guarantees_fines_amount = $flags->{CHARGES_GUARANTEES} ? $flags->{CHARGES_GUARANTEES}->{amount} : 0;
73 $fines_amount += $guarantees_fines_amount;
75 my $fee_limit = _fee_limit();
76 my $fine_blocked = $fines_amount > $fee_limit;
77 my $circ_blocked =( C4::Context->preference('OverduesBlockCirc') ne "noblock" && defined $flags->{ODUES}->{itemlist} ) ? 1 : 0;
79 no warnings; # any of these $kp->{fields} being concat'd could be undef
80 %ilspatron = (
81 name => $kp->{firstname} . " " . $kp->{surname},
82 id => $kp->{cardnumber}, # to SIP, the id is the BARCODE, not userid
83 password => $pw,
84 ptype => $kp->{categorycode}, # 'A'dult. Whatever.
85 dateexpiry => $dexpiry,
86 dateexpiry_iso => $kp->{dateexpiry},
87 birthdate => $dob,
88 birthdate_iso => $kp->{dateofbirth},
89 branchcode => $kp->{branchcode},
90 library_name => "", # only populated if needed, cached here
91 borrowernumber => $kp->{borrowernumber},
92 address => $adr,
93 home_phone => $kp->{phone},
94 email_addr => $kp->{email},
95 charge_ok => ( !$debarred && !$expired && !$fine_blocked && !$circ_blocked),
96 renew_ok => ( !$debarred && !$expired && !$fine_blocked),
97 recall_ok => ( !$debarred && !$expired && !$fine_blocked),
98 hold_ok => ( !$debarred && !$expired && !$fine_blocked),
99 card_lost => ( $kp->{lost} || $kp->{gonenoaddress} || $flags->{LOST} ),
100 claims_returned => 0,
101 fines => $fines_amount,
102 fees => 0, # currently not distinct from fines
103 recall_overdue => 0,
104 items_billed => 0,
105 screen_msg => 'Greetings from Koha. ' . $kp->{opacnote},
106 print_line => '',
107 items => [],
108 hold_items => $flags->{WAITING}->{itemlist},
109 overdue_items => $flags->{ODUES}->{itemlist},
110 too_many_overdue => $circ_blocked,
111 fine_items => [],
112 recall_items => [],
113 unavail_holds => [],
114 inet => ( !$debarred && !$expired ),
115 expired => $expired,
116 fee_limit => $fee_limit,
117 userid => $kp->{userid},
120 $debug and warn "patron fines: $ilspatron{fines} ... amountoutstanding: $kp->{amountoutstanding} ... CHARGES->amount: $flags->{CHARGES}->{amount}";
122 if ( $patron->is_debarred and $patron->debarredcomment ) {
123 $ilspatron{screen_msg} .= " -- " . $patron->debarredcomment;
125 if ( $circ_blocked ) {
126 $ilspatron{screen_msg} .= " -- " . "Patron has overdues";
128 for (qw(EXPIRED CHARGES CREDITS GNA LOST NOTES)) {
129 ($flags->{$_}) or next;
130 if ($_ ne 'NOTES' and $flags->{$_}->{message}) {
131 $ilspatron{screen_msg} .= " -- " . $flags->{$_}->{message}; # show all but internal NOTES
133 if ($flags->{$_}->{noissues}) {
134 foreach my $toggle (qw(charge_ok renew_ok recall_ok hold_ok inet)) {
135 $ilspatron{$toggle} = 0; # if we get noissues, disable everything
140 # FIXME: populate fine_items recall_items
141 $ilspatron{unavail_holds} = _get_outstanding_holds($kp->{borrowernumber});
143 my $pending_checkouts = $patron->pending_checkouts;
144 my @barcodes;
145 while ( my $c = $pending_checkouts->next ) {
146 push @barcodes, { barcode => $c->item->barcode };
148 $ilspatron{items} = \@barcodes;
150 $self = \%ilspatron;
151 $debug and warn Dumper($self);
152 syslog("LOG_DEBUG", "new ILS::Patron(%s): found patron '%s'", $patron_id,$self->{id});
153 bless $self, $type;
154 return $self;
158 # 0 means read-only
159 # 1 means read/write
161 my %fields = (
162 id => 0,
163 name => 0,
164 address => 0,
165 email_addr => 0,
166 home_phone => 0,
167 birthdate => 0,
168 birthdate_iso => 0,
169 dateexpiry => 0,
170 dateexpiry_iso => 0,
171 ptype => 0,
172 charge_ok => 0, # for patron_status[0] (inverted)
173 renew_ok => 0, # for patron_status[1] (inverted)
174 recall_ok => 0, # for patron_status[2] (inverted)
175 hold_ok => 0, # for patron_status[3] (inverted)
176 card_lost => 0, # for patron_status[4]
177 recall_overdue => 0,
178 currency => 1,
179 fee_limit => 0,
180 screen_msg => 1,
181 print_line => 1,
182 too_many_charged => 0, # for patron_status[5]
183 too_many_overdue => 0, # for patron_status[6]
184 too_many_renewal => 0, # for patron_status[7]
185 too_many_claim_return => 0, # for patron_status[8]
186 too_many_lost => 0, # for patron_status[9]
187 # excessive_fines => 0, # for patron_status[10]
188 # excessive_fees => 0, # for patron_status[11]
189 recall_overdue => 0, # for patron_status[12]
190 too_many_billed => 0, # for patron_status[13]
191 inet => 0, # EnvisionWare extension
194 our $AUTOLOAD;
196 sub DESTROY {
197 # be cool. needed for AUTOLOAD(?)
200 sub AUTOLOAD {
201 my $self = shift;
202 my $class = ref($self) or croak "$self is not an object";
203 my $name = $AUTOLOAD;
205 $name =~ s/.*://;
207 unless (exists $fields{$name}) {
208 croak "Cannot access '$name' field of class '$class'";
211 if (@_) {
212 $fields{$name} or croak "Field '$name' of class '$class' is READ ONLY.";
213 return $self->{$name} = shift;
214 } else {
215 return $self->{$name};
219 =head2 format
221 This method uses a template to build a string from a Koha::Patron object
222 If errors are encountered in processing template we log them and return nothing
224 =cut
226 sub format {
227 my ( $self, $template ) = @_;
229 if ($template) {
230 require Template;
231 require Koha::Patrons;
233 my $tt = Template->new();
235 my $patron = Koha::Patrons->find( $self->{borrowernumber} );
237 my $output;
238 eval {
239 $tt->process( \$template, { patron => $patron }, \$output );
241 if ( $@ ){
242 syslog("LOG_DEBUG", "Error processing template: $template");
243 return "";
245 return $output;
249 sub check_password {
250 my ( $self, $pwd ) = @_;
252 # you gotta give me something (at least ''), or no deal
253 return 0 unless defined $pwd;
255 # If the record has a NULL password, accept '' as match
256 return $pwd eq q{} unless $self->{password};
258 my $dbh = C4::Context->dbh;
259 my $ret = 0;
260 ($ret) = checkpw( $dbh, $self->{userid}, $pwd, undef, undef, 1 ); # dbh, userid, query, type, no_set_userenv
261 return $ret;
264 # A few special cases, not in AUTOLOADed %fields
265 sub fee_amount {
266 my $self = shift;
267 if ( $self->{fines} ) {
268 return $self->{fines};
270 return 0;
273 sub fines_amount {
274 my $self = shift;
275 return $self->fee_amount;
278 sub language {
279 my $self = shift;
280 return $self->{language} || '000'; # Unspecified
283 sub expired {
284 my $self = shift;
285 return $self->{expired};
289 # remove the hold on item item_id from my hold queue.
290 # return true if I was holding the item, false otherwise.
292 sub drop_hold {
293 my ($self, $item_id) = @_;
294 return if !$item_id;
295 my $result = 0;
296 foreach (qw(hold_items unavail_holds)) {
297 $self->{$_} or next;
298 for (my $i = 0; $i < scalar @{$self->{$_}}; $i++) {
299 my $held_item = $self->{$_}[$i]->{barcode} or next;
300 if ($held_item eq $item_id) {
301 splice @{$self->{$_}}, $i, 1;
302 $result++;
306 return $result;
309 # Accessor method for array_ref values, designed to get the "start" and "end" values
310 # from the SIP request. Note those incoming values are 1-indexed, not 0-indexed.
312 sub x_items {
313 my $self = shift;
314 my $array_var = shift or return;
315 my ($start, $end) = @_;
317 my $item_list = [];
318 if ($self->{$array_var}) {
319 if ($start && $start > 1) {
320 --$start;
322 else {
323 $start = 0;
325 if ( $end && $end < @{$self->{$array_var}} ) {
327 else {
328 $end = @{$self->{$array_var}};
329 --$end;
331 @{$item_list} = @{$self->{$array_var}}[ $start .. $end ];
334 return $item_list;
338 # List of outstanding holds placed
340 sub hold_items {
341 my $self = shift;
342 my $item_arr = $self->x_items('hold_items', @_);
343 foreach my $item (@{$item_arr}) {
344 my $item_obj = Koha::Items->find($item->{itemnumber});
345 $item->{barcode} = $item_obj ? $item_obj->barcode : undef;
347 return $item_arr;
350 sub overdue_items {
351 my $self = shift;
352 return $self->x_items('overdue_items', @_);
354 sub charged_items {
355 my $self = shift;
356 return $self->x_items('items', @_);
358 sub fine_items {
359 require Koha::Database;
360 require Template;
362 my $self = shift;
363 my $start = shift;
364 my $end = shift;
365 my $server = shift;
367 my @fees = Koha::Database->new()->schema()->resultset('Accountline')->search(
369 borrowernumber => $self->{borrowernumber},
370 amountoutstanding => { '>' => '0' },
374 $start = $start ? $start - 1 : 0;
375 $end = $end ? $end : scalar @fees - 1;
377 my $av_field_template = $server ? $server->{account}->{av_field_template} : undef;
378 $av_field_template ||= "[% accountline.description %] [% accountline.amountoutstanding | format('%.2f') %]";
380 my $tt = Template->new();
382 my @return_values;
383 for ( my $i = $start; $i <= $end; $i++ ) {
384 my $fee = $fees[$i];
386 my $output;
387 $tt->process( \$av_field_template, { accountline => $fee }, \$output );
388 push( @return_values, { barcode => $output } );
391 return \@return_values;
393 sub recall_items {
394 my $self = shift;
395 return $self->x_items('recall_items', @_);
397 sub unavail_holds {
398 my $self = shift;
399 return $self->x_items('unavail_holds', @_);
402 sub block {
403 my ($self, $card_retained, $blocked_card_msg) = @_;
404 foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') {
405 $self->{$field} = 0;
407 $self->{screen_msg} = "Block feature not implemented"; # $blocked_card_msg || "Card Blocked. Please contact library staff";
408 # TODO: not really affecting patron record
409 return $self;
412 sub enable {
413 my $self = shift;
414 foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') {
415 $self->{$field} = 1;
417 syslog("LOG_DEBUG", "Patron(%s)->enable: charge: %s, renew:%s, recall:%s, hold:%s",
418 $self->{id}, $self->{charge_ok}, $self->{renew_ok},
419 $self->{recall_ok}, $self->{hold_ok});
420 $self->{screen_msg} = "Enable feature not implemented."; # "All privileges restored."; # TODO: not really affecting patron record
421 return $self;
424 sub inet_privileges {
425 my $self = shift;
426 return $self->{inet} ? 'Y' : 'N';
429 sub _fee_limit {
430 return C4::Context->preference('noissuescharge') || 5;
433 sub excessive_fees {
434 my $self = shift;
435 return ($self->fee_amount and $self->fee_amount > $self->fee_limit);
438 sub excessive_fines {
439 my $self = shift;
440 return $self->excessive_fees; # excessive_fines is the same thing as excessive_fees for Koha
443 sub holds_blocked_by_excessive_fees {
444 my $self = shift;
445 return ( $self->fee_amount
446 && $self->fee_amount > C4::Context->preference("maxoutstanding") );
449 sub library_name {
450 my $self = shift;
451 unless ($self->{library_name}) {
452 my $library = Koha::Libraries->find( $self->{branchcode} );
453 $self->{library_name} = $library ? $library->branchname : '';
455 return $self->{library_name};
458 # Messages
461 sub invalid_patron {
462 my $self = shift;
463 return "Please contact library staff";
466 sub charge_denied {
467 my $self = shift;
468 return "Please contact library staff";
471 =head2 update_lastseen
473 $patron->update_lastseen();
475 Patron method to update lastseen field in borrower
476 to record that patron has been seen via sip connection
478 =cut
480 sub update_lastseen {
481 my $self = shift;
482 my $kohaobj = Koha::Patrons->find( $self->{borrowernumber} );
483 $kohaobj->track_login if $kohaobj; # track_login checks the pref
486 sub _get_address {
487 my $patron = shift;
489 my $address = $patron->{streetnumber} || q{};
490 for my $field (qw( roaddetails address address2 city state zipcode country))
492 next unless $patron->{$field};
493 if ($address) {
494 $address .= q{ };
495 $address .= $patron->{$field};
497 else {
498 $address .= $patron->{$field};
501 return $address;
504 sub _get_outstanding_holds {
505 my $borrowernumber = shift;
507 my $patron = Koha::Patrons->find( $borrowernumber );
508 my $holds = $patron->holds->search( { -or => [ { found => undef }, { found => { '!=' => 'W' } } ] } );
509 my @holds;
510 while ( my $hold = $holds->next ) {
511 my $item;
512 if ($hold->itemnumber) {
513 $item = $hold->item;
515 else {
516 # We need to return a barcode for the biblio so the client
517 # can request the biblio info
518 my $items = $hold->biblio->items;
519 $item = $items->count ? $items->next : undef;
521 my $unblessed_hold = $hold->unblessed;
523 $unblessed_hold->{barcode} = $item ? $item->barcode : undef;
525 push @holds, $unblessed_hold;
527 return \@holds;
530 =head2 build_patron_attributes_string
532 This method builds the part of the sip message for extended patron
533 attributes as defined in the sip config
535 =cut
537 sub build_patron_attributes_string {
538 my ( $self, $server ) = @_;
540 my $string = q{};
541 if ( $server->{account}->{patron_attribute} ) {
542 my @attributes_to_send =
543 ref $server->{account}->{patron_attribute} eq "ARRAY"
544 ? @{ $server->{account}->{patron_attribute} }
545 : ( $server->{account}->{patron_attribute} );
547 foreach my $a ( @attributes_to_send ) {
548 my @attributes = Koha::Patron::Attributes->search(
550 borrowernumber => $self->{borrowernumber},
551 code => $a->{code}
555 foreach my $attribute ( @attributes ) {
556 my $value = $attribute->attribute();
557 $string .= add_field( $a->{field}, $value );
562 return $string;
566 =head2 build_custom_field_string
568 This method builds the part of the sip message for custom patron fields as defined in the sip config
570 =cut
572 sub build_custom_field_string {
573 my ( $self, $server ) = @_;
575 my $string = q{};
577 if ( $server->{account}->{custom_patron_field} ) {
578 my @custom_fields =
579 ref $server->{account}->{custom_patron_field} eq "ARRAY"
580 ? @{ $server->{account}->{custom_patron_field} }
581 : $server->{account}->{custom_patron_field};
582 foreach my $custom_field ( @custom_fields ) {
583 $string .= maybe_add( $custom_field->{field}, $self->format( $custom_field->{template} ) ) if defined $custom_field->{field};
586 return $string;
590 __END__
592 =head1 EXAMPLES
594 our %patron_example = (
595 djfiander => {
596 name => "David J. Fiander",
597 id => 'djfiander',
598 password => '6789',
599 ptype => 'A', # 'A'dult. Whatever.
600 birthdate => '19640925',
601 address => '2 Meadowvale Dr. St Thomas, ON',
602 home_phone => '(519) 555 1234',
603 email_addr => 'djfiander@hotmail.com',
604 charge_ok => 1,
605 renew_ok => 1,
606 recall_ok => 0,
607 hold_ok => 1,
608 card_lost => 0,
609 claims_returned => 0,
610 fines => 100,
611 fees => 0,
612 recall_overdue => 0,
613 items_billed => 0,
614 screen_msg => '',
615 print_line => '',
616 items => [],
617 hold_items => [],
618 overdue_items => [],
619 fine_items => ['Computer Time'],
620 recall_items => [],
621 unavail_holds => [],
622 inet => 1,
626 From borrowers table:
627 +---------------------+--------------+------+-----+---------+----------------+
628 | Field | Type | Null | Key | Default | Extra |
629 +---------------------+--------------+------+-----+---------+----------------+
630 | borrowernumber | int(11) | NO | PRI | NULL | auto_increment |
631 | cardnumber | varchar(16) | YES | UNI | NULL | |
632 | surname | mediumtext | NO | | NULL | |
633 | firstname | text | YES | | NULL | |
634 | title | mediumtext | YES | | NULL | |
635 | othernames | mediumtext | YES | | NULL | |
636 | initials | text | YES | | NULL | |
637 | streetnumber | varchar(10) | YES | | NULL | |
638 | streettype | varchar(50) | YES | | NULL | |
639 | address | mediumtext | NO | | NULL | |
640 | address2 | text | YES | | NULL | |
641 | city | mediumtext | NO | | NULL | |
642 | state | mediumtext | YES | | NULL | |
643 | zipcode | varchar(25) | YES | | NULL | |
644 | country | text | YES | | NULL | |
645 | email | mediumtext | YES | | NULL | |
646 | phone | text | YES | | NULL | |
647 | mobile | varchar(50) | YES | | NULL | |
648 | fax | mediumtext | YES | | NULL | |
649 | emailpro | text | YES | | NULL | |
650 | phonepro | text | YES | | NULL | |
651 | B_streetnumber | varchar(10) | YES | | NULL | |
652 | B_streettype | varchar(50) | YES | | NULL | |
653 | B_address | varchar(100) | YES | | NULL | |
654 | B_address2 | text | YES | | NULL | |
655 | B_city | mediumtext | YES | | NULL | |
656 | B_state | mediumtext | YES | | NULL | |
657 | B_zipcode | varchar(25) | YES | | NULL | |
658 | B_country | text | YES | | NULL | |
659 | B_email | text | YES | | NULL | |
660 | B_phone | mediumtext | YES | | NULL | |
661 | dateofbirth | date | YES | | NULL | |
662 | branchcode | varchar(10) | NO | MUL | | |
663 | categorycode | varchar(10) | NO | MUL | | |
664 | dateenrolled | date | YES | | NULL | |
665 | dateexpiry | date | YES | | NULL | |
666 | gonenoaddress | tinyint(1) | YES | | NULL | |
667 | lost | tinyint(1) | YES | | NULL | |
668 | debarred | tinyint(1) | YES | | NULL | |
669 | contactname | mediumtext | YES | | NULL | |
670 | contactfirstname | text | YES | | NULL | |
671 | contacttitle | text | YES | | NULL | |
672 | borrowernotes | mediumtext | YES | | NULL | |
673 | relationship | varchar(100) | YES | | NULL | |
674 | ethnicity | varchar(50) | YES | | NULL | |
675 | ethnotes | varchar(255) | YES | | NULL | |
676 | sex | varchar(1) | YES | | NULL | |
677 | password | varchar(30) | YES | | NULL | |
678 | flags | int(11) | YES | | NULL | |
679 | userid | varchar(30) | YES | MUL | NULL | |
680 | opacnote | mediumtext | YES | | NULL | |
681 | contactnote | varchar(255) | YES | | NULL | |
682 | sort1 | varchar(80) | YES | | NULL | |
683 | sort2 | varchar(80) | YES | | NULL | |
684 | altcontactfirstname | varchar(255) | YES | | NULL | |
685 | altcontactsurname | varchar(255) | YES | | NULL | |
686 | altcontactaddress1 | varchar(255) | YES | | NULL | |
687 | altcontactaddress2 | varchar(255) | YES | | NULL | |
688 | altcontactaddress3 | varchar(255) | YES | | NULL | |
689 | altcontactstate | mediumtext | YES | | NULL | |
690 | altcontactzipcode | varchar(50) | YES | | NULL | |
691 | altcontactcountry | text | YES | | NULL | |
692 | altcontactphone | varchar(50) | YES | | NULL | |
693 | smsalertnumber | varchar(50) | YES | | NULL | |
694 | privacy | int(11) | NO | | 1 | |
695 +---------------------+--------------+------+-----+---------+----------------+
698 From C4::Members
700 $flags->{KEY}
701 {CHARGES}
702 {message} Message showing patron's credit or debt
703 {noissues} Set if patron owes >$5.00
704 {GNA} Set if patron gone w/o address
705 {message} "Borrower has no valid address"
706 {noissues} Set.
707 {LOST} Set if patron's card reported lost
708 {message} Message to this effect
709 {noissues} Set.
710 {DBARRED} Set if patron is debarred
711 {message} Message to this effect
712 {noissues} Set.
713 {NOTES} Set if patron has notes
714 {message} Notes about patron
715 {ODUES} Set if patron has overdue books
716 {message} "Yes"
717 {itemlist} ref-to-array: list of overdue books
718 {itemlisttext} Text list of overdue items
719 {WAITING} Set if there are items available that the patron reserved
720 {message} Message to this effect
721 {itemlist} ref-to-array: list of available items
723 =cut