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