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},
224 my $privilege = NCIP::User::Privilege->new();
225 $privilege->AgencyId($user->home_ou->shortname());
226 $privilege->AgencyUserPrivilegeType($pgt->name());
227 $privilege->ValidToDate($user->expire_date());
228 $privilege->ValidFromDate($user->create_date());
230 my $status = 'Active';
231 if (_expired($user)) {
233 } elsif ($U->is_true($user->barred())) {
235 } elsif (!$U->is_true($user->active())) {
236 $status = 'Inactive';
239 $privilege->UserPrivilegeStatus(
240 NCIP::User::PrivilegeStatus->new({
241 UserPrivilegeStatusType => $status
246 $optionalfields->UserPrivilege([$privilege]);
250 # Check for Block Or Trap.
251 if (grep {$_ eq 'Block Or Trap'} @$elements) {
254 # First, let's check if the profile is blocked from ILL.
255 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
256 my $block = NCIP::User::BlockOrTrap->new();
257 $block->AgencyId($user->home_ou->shortname());
258 $block->BlockOrTrapType('Block Interlibrary Loan');
259 push @$blocks, $block;
262 # Next, we loop through the user's standing penalties
263 # looking for blocks on CIRC, HOLD, and RENEW.
264 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
265 foreach my $penalty (@{$user->standing_penalties()}) {
266 next unless($penalty->standing_penalty->block_list());
267 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
268 my $ou = $U->simplereq(
270 'open-ils.pcrud.retrieve.aou',
271 $self->{session}->{authtoken},
272 $penalty->org_unit());
275 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
276 my $bot = NCIP::User::BlockOrTrap->new();
277 $bot->AgencyId($ou->shortname());
278 $bot->BlockOrTrapType('Block Checkout');
284 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
285 my $bot = NCIP::User::BlockOrTrap->new();
286 $bot->AgencyId($ou->shortname());
287 $bot->BlockOrTrapType('Block Holds');
293 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
294 my $bot = NCIP::User::BlockOrTrap->new();
295 $bot->AgencyId($ou->shortname());
296 $bot->BlockOrTrapType('Block Renewals');
301 # Stop after we report one of each, even if more
303 last if ($have_circ && $have_renew && $have_hold);
306 $optionalfields->BlockOrTrap($blocks);
309 $userdata->UserOptionalFields($optionalfields);
312 $response->data($userdata);
317 # Implementation functions that might be useful to a subclass.
319 # Login via OpenSRF to Evergreen.
323 # Get the authentication seed.
324 my $seed = $U->simplereq(
326 'open-ils.auth.authenticate.init',
327 $self->{config}->{credentials}->{username}
332 my $response = $U->simplereq(
334 'open-ils.auth.authenticate.complete',
336 username => $self->{config}->{credentials}->{username},
338 $seed . md5_hex($self->{config}->{credentials}->{password})
341 workstation => $self->{config}->{credentials}->{workstation}
345 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
346 $self->{session}->{authtime} = $response->{payload}->{authtime};
351 # Return 1 if we have a 'valid' authtoken, 0 if not.
355 # We use AppUtils to do the heavy lifting.
356 if (defined($self->{session})) {
357 if ($U->check_user_session($self->{session}->{authtoken})) {
364 # If we reach here, we don't have a session, so we are definitely
369 # private subroutines not meant to be used directly by subclasses.
370 # Most have to do with setup and/or state checking of implementation
373 # Find, load, and parse our configuration file:
377 # Find the configuration file via variables:
378 my $file = OILS_NCIP_CONFIG_DEFAULT;
379 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
381 $self->{config} = XMLin($file, NormaliseSpace => 2,
382 ForceArray => ['block_profile', 'stat_cat_entry']);
385 # Bootstrap OpenSRF::System and load the IDL.
389 my $bootstrap_config = $self->{config}->{bootstrap};
390 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
392 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
393 Fieldmapper->import(IDL => $idl);
396 # Login and then initialize some object data based on the
401 # Login to Evergreen.
404 # Retrieve the work_ou as an object.
405 my $work_ou = $U->simplereq(
407 'open-ils.pcrud.search.aou',
408 $self->{session}->{authtoken},
409 {shortname => $self->{config}->{credentials}->{work_ou}}
411 $self->{work_ou} = $work_ou->[0] if ($work_ou && @$work_ou);
413 # Load the barred groups as pgt objects into a blocked_profiles
415 $self->{blocked_profiles} = [];
416 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
418 my $pgt = $U->simplereq(
420 'open-ils.pcrud.retrieve.pgt',
421 $self->{session}->{authtoken},
423 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
425 my $result = $U->simplereq(
427 'open-ils.pcrud.search.pgt',
428 $self->{session}->{authtoken},
430 if ($result && @$result) {
431 map {push(@{$self->{blocked_profiles}}, $_)} @$result;
436 # Load the bib source if we're not using precats.
437 unless ($self->{config}->{items}->{use_precats}) {
438 # Retrieve the default
439 my $cbs = $U->simplereq(
441 'open-ils.pcrud.retrieve.cbs',
442 $self->{session}->{authtoken},
444 my $data = $self->{config}->{items}->{bib_source};
446 $data = $data->[0] if (ref($data) eq 'ARRAY');
448 my $result = $U->simplereq(
450 'open-ils.pcrud.retrieve.cbs',
451 $self->{session}->{authtoken},
453 $cbs = $result if ($result);
455 my $result = $U->simplereq(
457 'open-ils.pcrud.search.cbs',
458 $self->{session}->{authtoken},
460 if ($result && @$result) {
461 $cbs = $result->[0]; # Use the first one.
465 $self->{bib_source} = $cbs;
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 my $result = $U->simplereq(
479 'open-ils.cstore.direct.asset.stat_cat_entry.search',
481 stat_cat => $_->{stat_cat},
482 value => $_->{content},
486 if ($result && @$result) {
487 map {push(@{$self->{stat_cat_entries}}, $_)} @$result;
492 # Standalone, "helper" functions. These do not take an object or
495 # Check if a user is past their expiration date.
500 # Users might not expire. If so, they have no expire_date.
501 if ($user->expire_date()) {
502 my $expires = DateTime::Format::ISO8601->parse_datetime(
503 cleanse_ISO8601($user->expire_date())
505 my $now = DateTime->now()->epoch();
506 $expired = $now > $expires;