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