1 # ---------------------------------------------------------------
2 # Copyright © 2014 Jason J.A. Stephenson <jason@sigio.com>
4 # This file is part of NCIPServer.
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.
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.
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;
22 use XML::LibXML::Simple qw(XMLin);
24 use DateTime::Format::ISO8601;
25 use Digest::MD5 qw/md5_hex/;
27 use OpenSRF::Utils qw/:datetime/;
28 use OpenSRF::Utils::SettingsClient;
29 use OpenILS::Utils::Fieldmapper;
30 use OpenILS::Application::AppUtils;
31 use OpenILS::Const qw/:const/;
36 # We need a bunch of NCIP::* objects.
40 use NCIP::User::OptionalFields;
41 use NCIP::User::AddressInformation;
43 use NCIP::User::BlockOrTrap;
44 use NCIP::User::Privilege;
45 use NCIP::User::PrivilegeStatus;
46 use NCIP::StructuredPersonalUserName;
47 use NCIP::StructuredAddress;
48 use NCIP::ElectronicAddress;
50 # Inherit from NCIP::ILS.
51 use parent qw(NCIP::ILS);
53 # Default values we define for things that might be missing in our
54 # runtime environment or configuration file that absolutely must have
57 # OILS_NCIP_CONFIG_DEFAULT is the default location to find our
58 # driver's configuration file. This location can be overridden by
59 # setting the path in the OILS_NCIP_CONFIG environment variable.
61 # BIB_SOURCE_DEFAULT is the config.bib_source.id to use when creating
62 # "short" bibs. It is used only if no entry is supplied in the
63 # configuration file. The provided default is 2, the id of the
64 # "System Local" source that comes with a default Evergreen
67 OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
68 BIB_SOURCE_DEFAULT => 2
71 # A common Evergreen code shortcut to use AppUtils:
72 my $U = 'OpenILS::Application::AppUtils';
74 # The usual constructor:
77 $class = ref($class) if (ref $class);
79 # Instantiate our parent with the rest of the arguments. It
80 # creates a blessed hashref.
81 my $self = $class->SUPER::new(@_);
83 # Look for our configuration file, load, and parse it:
86 # Bootstrap OpenSRF and prepare some OpenILS components.
89 # Initialize the rest of our internal state.
99 # Check our session and login if necessary.
100 $self->login() unless ($self->checkauth());
102 my $message_type = $self->parse_request_type($request);
104 # Let's go ahead and create our response object. We need this even
105 # if there is a problem.
106 my $response = NCIP::Response->new({type => $message_type . "Response"});
107 $response->header($self->make_header($request));
109 # Need to parse the request object to get the user barcode.
110 my ($barcode, $idfield) = $self->find_user_barcode($request);
112 # If we can't find a barcode, report a problem.
114 $idfield = 'AuthenticationInputType' unless ($idfield);
115 # Fill in a problem object and stuff it in the response.
116 my $problem = NCIP::Problem->new();
117 $problem->ProblemType('Needed Data Missing');
118 $problem->ProblemDetail('Cannot find user barcode in message.');
119 $problem->ProblemElement($idfield);
120 $problem->ProblemValue('Barcode');
121 $response->problem($problem);
125 # Look up our patron by barcode:
126 my $user = $U->simplereq(
128 'open-ils.actor.user.fleshed.retrieve_by_barcode',
129 $self->{session}->{authtoken},
134 # Check for a failure, or a deleted, inactive, or expired user,
135 # and if so, return empty userdata.
136 if (!$user || $U->event_code($user) || $U->is_true($user->deleted())
137 || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$user->cards()}) {
139 my $problem = NCIP::Problem->new();
140 $problem->ProblemType('Unknown User');
141 $problem->ProblemDetail("User with barcode $barcode unknown");
142 $problem->ProblemElement($idfield);
143 $problem->ProblemValue($barcode);
144 $response->problem($problem);
148 # We got the information, so lets fill in our userdata.
149 my $userdata = NCIP::User->new();
151 # Make an array of the user's active barcodes.
153 foreach my $card (@{$user->cards()}) {
154 if ($U->is_true($card->active())) {
155 my $id = NCIP::User::Id->new({
156 UserIdentifierType => 'Barcode',
157 UserIdentifierValue => $card->barcode()
162 $userdata->UserId($ids);
164 # Check if they requested any optional fields and return those.
165 my $elements = $request->{$message_type}->{UserElementType};
167 $elements = [$elements] unless (ref $elements eq 'ARRAY');
168 my $optionalfields = NCIP::User::OptionalFields->new();
170 # First, we'll look for name information.
171 if (grep {$_ eq 'Name Information'} @$elements) {
172 my $name = NCIP::StructuredPersonalUserName->new();
173 $name->Surname($user->family_name());
174 $name->GivenName($user->first_given_name());
175 $name->Prefix($user->prefix());
176 $name->Suffix($user->suffix());
177 $optionalfields->NameInformation($name);
180 # Next, check for user address information.
181 if (grep {$_ eq 'User Address Information'} @$elements) {
184 # See if the user has any valid, physcial addresses.
185 foreach my $addr (@{$user->addresses()}) {
186 next if ($U->is_true($addr->pending()));
187 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
188 my $physical = NCIP::StructuredAddress->new();
189 $physical->Line1($addr->street1());
190 $physical->Line2($addr->street2());
191 $physical->Locality($addr->city());
192 $physical->Region($addr->state());
193 $physical->PostalCode($addr->post_code());
194 $physical->Country($addr->country());
195 $address->PhysicalAddress($physical);
196 push @$addresses, $address;
199 # Right now, we're only sharing email address if the user
200 # has it. We don't share phone numbers.
201 if ($user->email()) {
202 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
203 $address->ElectronicAddress(
204 NCIP::ElectronicAddress->new({
205 Type=>'Email Address',
209 push @$addresses, $address;
212 $optionalfields->UserAddressInformation($addresses);
215 # Check for User Privilege.
216 if (grep {$_ eq 'User Privilege'} @$elements) {
217 # Get the user's group:
218 my $pgt = $U->simplereq(
220 'open-ils.pcrud.retrieve.pgt',
221 $self->{session}->{authtoken},
225 my $privilege = NCIP::User::Privilege->new();
226 $privilege->AgencyId($user->home_ou->shortname());
227 $privilege->AgencyUserPrivilegeType($pgt->name());
228 $privilege->ValidToDate($user->expire_date());
229 $privilege->ValidFromDate($user->create_date());
231 my $status = 'Active';
232 if (_expired($user)) {
234 } elsif ($U->is_true($user->barred())) {
236 } elsif (!$U->is_true($user->active())) {
237 $status = 'Inactive';
240 $privilege->UserPrivilegeStatus(
241 NCIP::User::PrivilegeStatus->new({
242 UserPrivilegeStatusType => $status
247 $optionalfields->UserPrivilege([$privilege]);
251 # Check for Block Or Trap.
252 if (grep {$_ eq 'Block Or Trap'} @$elements) {
255 # First, let's check if the profile is blocked from ILL.
256 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
257 my $block = NCIP::User::BlockOrTrap->new();
258 $block->AgencyId($user->home_ou->shortname());
259 $block->BlockOrTrapType('Block Interlibrary Loan');
260 push @$blocks, $block;
263 # Next, we loop through the user's standing penalties
264 # looking for blocks on CIRC, HOLD, and RENEW.
265 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
266 foreach my $penalty (@{$user->standing_penalties()}) {
267 next unless($penalty->standing_penalty->block_list());
268 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
269 my $ou = $U->simplereq(
271 'open-ils.pcrud.retrieve.aou',
272 $self->{session}->{authtoken},
277 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
278 my $bot = NCIP::User::BlockOrTrap->new();
279 $bot->AgencyId($ou->shortname());
280 $bot->BlockOrTrapType('Block Checkout');
286 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
287 my $bot = NCIP::User::BlockOrTrap->new();
288 $bot->AgencyId($ou->shortname());
289 $bot->BlockOrTrapType('Block Holds');
295 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
296 my $bot = NCIP::User::BlockOrTrap->new();
297 $bot->AgencyId($ou->shortname());
298 $bot->BlockOrTrapType('Block Renewals');
303 # Stop after we report one of each, even if more
305 last if ($have_circ && $have_renew && $have_hold);
308 $optionalfields->BlockOrTrap($blocks);
311 $userdata->UserOptionalFields($optionalfields);
314 $response->data($userdata);
319 # Implementation functions that might be useful to a subclass.
321 # Login via OpenSRF to Evergreen.
325 # Get the authentication seed.
326 my $seed = $U->simplereq(
328 'open-ils.auth.authenticate.init',
329 $self->{config}->{credentials}->{username}
334 my $response = $U->simplereq(
336 'open-ils.auth.authenticate.complete',
338 username => $self->{config}->{credentials}->{username},
340 $seed . md5_hex($self->{config}->{credentials}->{password})
343 workstation => $self->{config}->{credentials}->{workstation}
347 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
348 $self->{session}->{authtime} = $response->{payload}->{authtime};
353 # Return 1 if we have a 'valid' authtoken, 0 if not.
357 # We use AppUtils to do the heavy lifting.
358 if (defined($self->{session})) {
359 if ($U->check_user_session($self->{session}->{authtoken})) {
366 # If we reach here, we don't have a session, so we are definitely
371 # private subroutines not meant to be used directly by subclasses.
372 # Most have to do with setup and/or state checking of implementation
375 # Find, load, and parse our configuration file:
379 # Find the configuration file via variables:
380 my $file = OILS_NCIP_CONFIG_DEFAULT;
381 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
383 $self->{config} = XMLin($file, NormaliseSpace => 2,
384 ForceArray => ['block_profile', 'stat_cat_entry']);
387 # Bootstrap OpenSRF::System and load the IDL.
391 my $bootstrap_config = $self->{config}->{bootstrap};
392 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
394 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
395 Fieldmapper->import(IDL => $idl);
398 # Login and then initialize some object data based on the
403 # Login to Evergreen.
406 # Retrieve the work_ou as an object.
407 $self->{work_ou} = $U->simplereq(
409 'open-ils.pcrud.search.aou',
410 $self->{session}->{authtoken},
411 {shortname => $self->{config}->{credentials}->{work_ou}}
414 # Load the barred groups as pgt objects into a blocked_profiles
416 $self->{blocked_profiles} = [];
417 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
420 $pgt = $U->simplereq(
422 'open-ils.pcrud.retrieve.pgt',
423 $self->{session}->{authtoken},
427 $pgt = $U->simplereq(
429 'open-ils.pcrud.search.pgt',
430 $self->{session}->{authtoken},
434 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
437 # Load the bib source if we're not using precats.
438 unless ($self->{config}->{items}->{use_precats}) {
439 # Retrieve the default
440 $self->{bib_source} = $U->simplereq(
442 'open-ils.pcrud.retrieve.cbs',
443 $self->{session}->{authtoken},
445 my $data = $self->{config}->{items}->{bib_source};
447 $data = $data->[0] if (ref($data) eq 'ARRAY');
450 $result = $U->simplereq(
452 'open-ils.pcrud.retrieve.cbs',
453 $self->{session}->{authtoken},
457 $result = $U->simplereq(
459 'open-ils.pcrud.search.cbs',
460 $self->{session}->{authtoken},
464 $self->{bib_source} = $result if ($result);
468 # Load the required asset.stat_cat_entries:
469 $self->{stat_cat_entries} = [];
470 foreach (@{$self->{config}->{items}->{stat_cat_entry}}) {
471 # Must have the stat_cat attr and the name, so we must have a
474 # We want to limit the search to the work org and its
476 my $ancestors = $U->get_org_ancestors($self->{work_ou}->id());
477 # We only want 1, so we don't do .atomic.
478 my $result = $U->simplereq(
480 'open-ils.cstore.direct.asset.stat_cat_entry.search',
482 stat_cat => $_->{stat_cat},
483 value => $_->{content},
487 push(@{$self->{stat_cat_entries}}, $result) if ($result);
491 # Standalone, "helper" functions. These do not take an object or
494 # Check if a user is past their expiration date.
499 # Users might not expire. If so, they have no expire_date.
500 if ($user->expire_date()) {
501 my $expires = DateTime::Format::ISO8601->parse_datetime(
502 cleanse_ISO8601($user->expire_date())
504 my $now = DateTime->now()->epoch();
505 $expired = $now > $expires;