]> git.evergreen-ils.org Git - working/NCIPServer.git/blob - lib/NCIP/ILS/Evergreen.pm
Flesh user's home_ou in Evergreen->lookupuser.
[working/NCIPServer.git] / lib / NCIP / ILS / Evergreen.pm
1 # ---------------------------------------------------------------
2 # Copyright © 2014 Jason J.A. Stephenson <jason@sigio.com>
3 #
4 # This file is part of NCIPServer.
5 #
6 # NCIPServer is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # NCIPServer is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with NCIPServer.  If not, see <http://www.gnu.org/licenses/>.
18 # ---------------------------------------------------------------
19 package NCIP::ILS::Evergreen;
20
21 use Modern::Perl;
22 use XML::LibXML::Simple qw(XMLin);
23 use DateTime;
24 use DateTime::Format::ISO8601;
25 use Digest::MD5 qw/md5_hex/;
26 use OpenSRF::System;
27 use OpenSRF::Utils qw/:datetime/;
28 use OpenSRF::Utils::SettingsClient;
29 use OpenILS::Utils::Fieldmapper;
30 use OpenILS::Utils::CStoreEditor qw/:funcs/;
31 use OpenILS::Application::AppUtils;
32 use OpenILS::Const qw/:const/;
33 use MARC::Record;
34 use MARC::Field;
35 use MARC::File::XML;
36
37 # We need a bunch of NCIP::* objects.
38 use NCIP::Response;
39 use NCIP::Problem;
40 use NCIP::User;
41 use NCIP::User::OptionalFields;
42 use NCIP::User::AddressInformation;
43 use NCIP::User::Id;
44 use NCIP::User::BlockOrTrap;
45 use NCIP::User::Privilege;
46 use NCIP::User::PrivilegeStatus;
47 use NCIP::StructuredPersonalUserName;
48 use NCIP::StructuredAddress;
49 use NCIP::ElectronicAddress;
50
51 # Inherit from NCIP::ILS.
52 use parent qw(NCIP::ILS);
53
54 # Default values we define for things that might be missing in our
55 # runtime environment or configuration file that absolutely must have
56 # values.
57 #
58 # OILS_NCIP_CONFIG_DEFAULT is the default location to find our
59 # driver's configuration file.  This location can be overridden by
60 # setting the path in the OILS_NCIP_CONFIG environment variable.
61 #
62 # BIB_SOURCE_DEFAULT is the config.bib_source.id to use when creating
63 # "short" bibs.  It is used only if no entry is supplied in the
64 # configuration file.  The provided default is 2, the id of the
65 # "System Local" source that comes with a default Evergreen
66 # installation.
67 use constant {
68     OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
69     BIB_SOURCE_DEFAULT => 2
70 };
71
72 # A common Evergreen code shortcut to use AppUtils:
73 my $U = 'OpenILS::Application::AppUtils';
74
75 # The usual constructor:
76 sub new {
77     my $class = shift;
78     $class = ref($class) if (ref $class);
79
80     # Instantiate our parent with the rest of the arguments.  It
81     # creates a blessed hashref.
82     my $self = $class->SUPER::new(@_);
83
84     # Look for our configuration file, load, and parse it:
85     $self->_configure();
86
87     # Bootstrap OpenSRF and prepare some OpenILS components.
88     $self->_bootstrap();
89
90     # Initialize the rest of our internal state.
91     $self->_init();
92
93     return $self;
94 }
95
96 sub lookupuser {
97     my $self = shift;
98     my $request = shift;
99
100     # Check our session and login if necessary.
101     $self->login() unless ($self->checkauth());
102
103     my $message_type = $self->parse_request_type($request);
104
105     # Let's go ahead and create our response object. We need this even
106     # if there is a problem.
107     my $response = NCIP::Response->new({type => $message_type . "Response"});
108     $response->header($self->make_header($request));
109
110     # Need to parse the request object to get the user barcode.
111     my ($barcode, $idfield) = $self->find_user_barcode($request);
112
113     # If we can't find a barcode, report a problem.
114     unless ($barcode) {
115         $idfield = 'AuthenticationInputType' unless ($idfield);
116         # Fill in a problem object and stuff it in the response.
117         my $problem = NCIP::Problem->new();
118         $problem->ProblemType('Needed Data Missing');
119         $problem->ProblemDetail('Cannot find user barcode in message.');
120         $problem->ProblemElement($idfield);
121         $problem->ProblemValue('Barcode');
122         $response->problem($problem);
123         return $response;
124     }
125
126     # Look up our patron by barcode:
127     my $user = $U->simplereq(
128         'open-ils.actor',
129         'open-ils.actor.user.fleshed.retrieve_by_barcode',
130         $self->{session}->{authtoken},
131         $barcode,
132         1
133     );
134
135     # Check for a failure, or a deleted, inactive, or expired user,
136     # and if so, return empty userdata.
137     if (!$user || $U->event_code($user) || $U->is_true($user->deleted())
138             || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$user->cards()}) {
139
140         my $problem = NCIP::Problem->new();
141         $problem->ProblemType('Unknown User');
142         $problem->ProblemDetail("User with barcode $barcode unknown");
143         $problem->ProblemElement($idfield);
144         $problem->ProblemValue($barcode);
145         $response->problem($problem);
146         return $response;
147     }
148
149     # We got the information, so lets fill in our userdata.
150     my $userdata = NCIP::User->new();
151
152     # Make an array of the user's active barcodes.
153     my $ids = [];
154     foreach my $card (@{$user->cards()}) {
155         if ($U->is_true($card->active())) {
156             my $id = NCIP::User::Id->new({
157                 UserIdentifierType => 'Barcode',
158                 UserIdentifierValue => $card->barcode()
159             });
160             push(@$ids, $id);
161         }
162     }
163     $userdata->UserId($ids);
164
165     # Check if they requested any optional fields and return those.
166     my $elements = $request->{$message_type}->{UserElementType};
167     if ($elements) {
168         $elements = [$elements] unless (ref $elements eq 'ARRAY');
169         my $optionalfields = NCIP::User::OptionalFields->new();
170
171         # First, we'll look for name information.
172         if (grep {$_ eq 'Name Information'} @$elements) {
173             my $name = NCIP::StructuredPersonalUserName->new();
174             $name->Surname($user->family_name());
175             $name->GivenName($user->first_given_name());
176             $name->Prefix($user->prefix());
177             $name->Suffix($user->suffix());
178             $optionalfields->NameInformation($name);
179         }
180
181         # Next, check for user address information.
182         if (grep {$_ eq 'User Address Information'} @$elements) {
183             my $addresses = [];
184
185             # See if the user has any valid, physcial addresses.
186             foreach my $addr (@{$user->addresses()}) {
187                 next if ($U->is_true($addr->pending()));
188                 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
189                 my $physical = NCIP::StructuredAddress->new();
190                 $physical->Line1($addr->street1());
191                 $physical->Line2($addr->street2());
192                 $physical->Locality($addr->city());
193                 $physical->Region($addr->state());
194                 $physical->PostalCode($addr->post_code());
195                 $physical->Country($addr->country());
196                 $address->PhysicalAddress($physical);
197                 push @$addresses, $address;
198             }
199
200             # Right now, we're only sharing email address if the user
201             # has it. We don't share phone numbers.
202             if ($user->email()) {
203                 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
204                 $address->ElectronicAddress(
205                     NCIP::ElectronicAddress->new({
206                         Type=>'Email Address',
207                         Data=>$user->email()
208                     })
209                 );
210                 push @$addresses, $address;
211             }
212
213             $optionalfields->UserAddressInformation($addresses);
214         }
215
216         # Check for User Privilege.
217         if (grep {$_ eq 'User Privilege'} @$elements) {
218             # Get the user's group:
219             my $pgt = $self->editor->retrieve_permission_grp_tree($user->profile());
220             if ($pgt) {
221                 my $privilege = NCIP::User::Privilege->new();
222                 $privilege->AgencyId($user->home_ou->shortname());
223                 $privilege->AgencyUserPrivilegeType($pgt->name());
224                 $privilege->ValidToDate($user->expire_date());
225                 $privilege->ValidFromDate($user->create_date());
226
227                 my $status = 'Active';
228                 if (_expired($user)) {
229                     $status = 'Expired';
230                 } elsif ($U->is_true($user->barred())) {
231                     $status = 'Barred';
232                 } elsif (!$U->is_true($user->active())) {
233                     $status = 'Inactive';
234                 }
235                 if ($status) {
236                     $privilege->UserPrivilegeStatus(
237                         NCIP::User::PrivilegeStatus->new({
238                             UserPrivilegeStatusType => $status
239                         })
240                     );
241                 }
242
243                 $optionalfields->UserPrivilege([$privilege]);
244             }
245         }
246
247         # Check for Block Or Trap.
248         if (grep {$_ eq 'Block Or Trap'} @$elements) {
249             my $blocks = [];
250
251             # First, let's check if the profile is blocked from ILL.
252             if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
253                 my $block = NCIP::User::BlockOrTrap->new();
254                 $block->AgencyId($user->home_ou->shortname());
255                 $block->BlockOrTrapType('Block Interlibrary Loan');
256                 push @$blocks, $block;
257             }
258
259             # Next, we loop through the user's standing penalties
260             # looking for blocks on CIRC, HOLD, and RENEW.
261             my ($have_circ, $have_renew, $have_hold) = (0,0,0);
262             foreach my $penalty (@{$user->standing_penalties()}) {
263                 next unless($penalty->standing_penalty->block_list());
264                 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
265                 my $ou = $self->editor->retrieve_actor_org_unit($penalty->org_unit());
266
267                 # Block checkout.
268                 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
269                     my $bot = NCIP::User::BlockOrTrap->new();
270                     $bot->AgencyId($ou->shortname());
271                     $bot->BlockOrTrapType('Block Checkout');
272                     push @$blocks, $bot;
273                     $have_circ = 1;
274                 }
275
276                 # Block holds.
277                 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
278                     my $bot = NCIP::User::BlockOrTrap->new();
279                     $bot->AgencyId($ou->shortname());
280                     $bot->BlockOrTrapType('Block Holds');
281                     push @$blocks, $bot;
282                     $have_hold = 1;
283                 }
284
285                 # Block renewals.
286                 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
287                     my $bot = NCIP::User::BlockOrTrap->new();
288                     $bot->AgencyId($ou->shortname());
289                     $bot->BlockOrTrapType('Block Renewals');
290                     push @$blocks, $bot;
291                     $have_renew = 1;
292                 }
293
294                 # Stop after we report one of each, even if more
295                 # blocks remain.
296                 last if ($have_circ && $have_renew && $have_hold);
297             }
298
299             $optionalfields->BlockOrTrap($blocks);
300         }
301
302         $userdata->UserOptionalFields($optionalfields);
303     }
304
305     $response->data($userdata);
306
307     return $response;
308 }
309
310 # Implementation functions that might be useful to a subclass.
311
312 # Get a CStoreEditor:
313 sub editor {
314     my $self = shift;
315
316     # If we have an editor, check the validity of the auth session, then
317     # invalidate the editor if the session is not valid.
318     if ($self->{editor}) {
319         undef($self->{editor}) unless ($self->checkauth());
320     }
321
322     # If we don't have an editor, make a new one.
323     unless (defined($self->{editor})) {
324         $self->login() unless ($self->checkauth());
325         $self->{editor} = new_editor(authtoken=>$self->{session}->{authtoken});
326     }
327
328     return $self->{editor};
329 }
330
331 # Login via OpenSRF to Evergreen.
332 sub login {
333     my $self = shift;
334
335     # Get the authentication seed.
336     my $seed = $U->simplereq(
337         'open-ils.auth',
338         'open-ils.auth.authenticate.init',
339         $self->{config}->{credentials}->{username}
340     );
341
342     # Actually login.
343     if ($seed) {
344         my $response = $U->simplereq(
345             'open-ils.auth',
346             'open-ils.auth.authenticate.complete',
347             {
348                 username => $self->{config}->{credentials}->{username},
349                 password => md5_hex(
350                     $seed . md5_hex($self->{config}->{credentials}->{password})
351                 ),
352                 type => 'staff',
353                 workstation => $self->{config}->{credentials}->{workstation}
354             }
355         );
356         if ($response) {
357             $self->{session}->{authtoken} = $response->{payload}->{authtoken};
358             $self->{session}->{authtime} = $response->{payload}->{authtime};
359         }
360     }
361 }
362
363 # Return 1 if we have a 'valid' authtoken, 0 if not.
364 sub checkauth {
365     my $self = shift;
366
367     # We implement our own version of this function, rather than rely
368     # on CStoreEditor, because we may want to check this at times that
369     # we don't have a CStoreEditor.
370
371     # We use AppUtils to do the heavy lifting.
372     if (defined($self->{session})) {
373         if ($U->check_user_session($self->{session}->{authtoken})) {
374             return 1;
375         } else {
376             return 0;
377         }
378     }
379
380     # If we reach here, we don't have a session, so we are definitely
381     # not logged in.
382     return 0;
383 }
384
385 # private subroutines not meant to be used directly by subclasses.
386 # Most have to do with setup and/or state checking of implementation
387 # components.
388
389 # Find, load, and parse our configuration file:
390 sub _configure {
391     my $self = shift;
392
393     # Find the configuration file via variables:
394     my $file = OILS_NCIP_CONFIG_DEFAULT;
395     $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
396
397     $self->{config} = XMLin($file, NormaliseSpace => 2,
398                             ForceArray => ['block_profile', 'stat_cat_entry']);
399 }
400
401 # Bootstrap OpenSRF::System, load the IDL, and initialize the
402 # CStoreEditor module.
403 sub _bootstrap {
404     my $self = shift;
405
406     my $bootstrap_config = $self->{config}->{bootstrap};
407     OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
408
409     my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
410     Fieldmapper->import(IDL => $idl);
411
412     OpenILS::Utils::CStoreEditor->init;
413 }
414
415 # Login and then initialize some object data based on the
416 # configuration.
417 sub _init {
418     my $self = shift;
419
420     # Login to Evergreen.
421     $self->login();
422
423     # Create an editor.
424     my $e = $self->editor();
425
426     # Retrieve the work_ou as an object.
427     my $work_ou = $e->search_actor_org_unit(
428         {shortname => $self->{config}->{credentials}->{work_ou}}
429     );
430     $self->{work_ou} = $work_ou->[0] if ($work_ou && @$work_ou);
431
432     # Load the barred groups as pgt objects into a blocked_profiles
433     # list.
434     $self->{blocked_profiles} = [];
435     foreach (@{$self->{config}->{patrons}->{block_profile}}) {
436         if (ref $_) {
437             my $pgt = $e->retrieve_permission_grp_tree($_->{grp});
438             push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
439         } else {
440             my $result = $e->search_permission_grp_tree({name => $_});
441             if ($result && @$result) {
442                 map {push(@{$self->{blocked_profiles}}, $_)} @$result;
443             }
444         }
445     }
446
447     # Load the bib source if we're not using precats.
448     unless ($self->{config}->{items}->{use_precats}) {
449         # Retrieve the default
450         my $cbs = $e->retrieve_config_bib_source(BIB_SOURCE_DEFAULT);
451         my $data = $self->{config}->{items}->{bib_source};
452         if ($data) {
453             $data = $data->[0] if (ref($data) eq 'ARRAY');
454             if (ref $data) {
455                 my $result = $e->retrieve_config_bib_source($data->{cbs});
456                 $cbs = $result if ($result);
457             } else {
458                 my $result = $e->search_config_bib_source({source => $data});
459                 if ($result && @$result) {
460                     $cbs = $result->[0]; # Use the first one.
461                 }
462             }
463         }
464         $self->{bib_source} = $cbs;
465     }
466
467     # Load the required asset.stat_cat_entries:
468     $self->{stat_cat_entries} = [];
469     foreach (@{$self->{config}->{items}->{stat_cat_entry}}) {
470         # Must have the stat_cat attr and the name, so we must have a
471         # reference.
472         next unless(ref $_);
473         # We want to limit the search to the work org and its
474         # ancestors.
475         my $ancestors = $U->get_org_ancestors($self->{work_ou}->id());
476         my $result = $e->search_asset_stat_cat_entry(
477             {
478                 stat_cat => $_->{stat_cat},
479                 value => $_->{content},
480                 owner => $ancestors
481             }
482         );
483         if ($result && @$result) {
484             map {push(@{$self->{stat_cat_entries}}, $_)} @$result;
485         }
486     }
487 }
488
489 # Standalone, "helper" functions.  These do not take an object or
490 # class reference.
491
492 # Check if a user is past their expiration date.
493 sub _expired {
494     my $user = shift;
495     my $expired = 0;
496
497     # Users might not expire.  If so, they have no expire_date.
498     if ($user->expire_date()) {
499         my $expires = DateTime::Format::ISO8601->parse_datetime(
500             cleanse_ISO8601($user->expire_date())
501         )->epoch();
502         my $now = DateTime->now()->epoch();
503         $expired = $now > $expires;
504     }
505
506     return $expired;
507 }
508
509 1;