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::AppSession;
28 use OpenSRF::Utils qw/:datetime/;
29 use OpenSRF::Utils::SettingsClient;
30 use OpenILS::Utils::Fieldmapper;
31 use OpenILS::Utils::Normalize qw(clean_marc);
32 use OpenILS::Application::AppUtils;
33 use OpenILS::Const qw/:const/;
37 use List::MoreUtils qw/uniq/;
38 use POSIX qw/strftime/;
40 # We need a bunch of NCIP::* objects.
44 use NCIP::User::OptionalFields;
45 use NCIP::User::AddressInformation;
47 use NCIP::User::BlockOrTrap;
48 use NCIP::User::Privilege;
49 use NCIP::User::PrivilegeStatus;
50 use NCIP::StructuredPersonalUserName;
51 use NCIP::StructuredAddress;
52 use NCIP::ElectronicAddress;
53 use NCIP::PhysicalAddress;
56 use NCIP::Item::OptionalFields;
57 use NCIP::Item::BibliographicDescription;
58 use NCIP::Item::BibliographicItemId;
59 use NCIP::Item::BibliographicRecordId;
60 use NCIP::Item::Description;
62 # Inherit from NCIP::ILS.
63 use parent qw(NCIP::ILS);
67 Evergreen - Evergreen driver for NCIPServer
71 my $ils = NCIP::ILS::Evergreen->new(name => $config->{NCIP.ils.value});
75 NCIP::ILS::Evergreen is the default driver for Evergreen and
76 NCIPServer. It was initially developed to work with Auto-Graphics'
77 SHAREit software using a subset of an unspecified ILL/DCB profile.
81 # Default values we define for things that might be missing in our
82 # runtime environment or configuration file that absolutely must have
85 # OILS_NCIP_CONFIG_DEFAULT is the default location to find our
86 # driver's configuration file. This location can be overridden by
87 # setting the path in the OILS_NCIP_CONFIG environment variable.
89 # BIB_SOURCE_DEFAULT is the config.bib_source.id to use when creating
90 # "short" bibs. It is used only if no entry is supplied in the
91 # configuration file. The provided default is 2, the id of the
92 # "System Local" source that comes with a default Evergreen
95 OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
96 BIB_SOURCE_DEFAULT => 2
99 # A common Evergreen code shortcut to use AppUtils:
100 my $U = 'OpenILS::Application::AppUtils';
102 # The usual constructor:
105 $class = ref($class) if (ref $class);
107 # Instantiate our parent with the rest of the arguments. It
108 # creates a blessed hashref.
109 my $self = $class->SUPER::new(@_);
111 # Look for our configuration file, load, and parse it:
114 # Bootstrap OpenSRF and prepare some OpenILS components.
117 # Initialize the rest of our internal state.
123 =head1 HANDLER METHODS
127 $ils->lookupuser($request);
129 Processes a LookupUser request.
137 # Check our session and login if necessary.
138 $self->login() unless ($self->checkauth());
140 my $message_type = $self->parse_request_type($request);
142 # Let's go ahead and create our response object. We need this even
143 # if there is a problem.
144 my $response = NCIP::Response->new({type => $message_type . "Response"});
145 $response->header($self->make_header($request));
147 # Need to parse the request object to get the user barcode.
148 my ($barcode, $idfield) = $self->find_user_barcode($request);
150 # If we did not find a barcode, then report the problem.
151 if (ref($barcode) eq 'NCIP::Problem') {
152 $response->problem($barcode);
156 # Look up our patron by barcode:
157 my $user = $self->retrieve_user_by_barcode($barcode, $idfield);
158 if (ref($user) eq 'NCIP::Problem') {
159 $response->problem($user);
163 # We got the information, so lets fill in our userdata.
164 my $userdata = NCIP::User->new();
166 # Make an array of the user's active barcodes.
168 foreach my $card (@{$user->cards()}) {
169 if ($U->is_true($card->active())) {
170 my $id = NCIP::User::Id->new({
171 UserIdentifierType => 'Barcode',
172 UserIdentifierValue => $card->barcode()
177 $userdata->UserId($ids);
179 # Check if they requested any optional fields and return those.
180 my $elements = $request->{$message_type}->{UserElementType};
182 $elements = [$elements] unless (ref $elements eq 'ARRAY');
183 my $optionalfields = $self->handle_user_elements($user, $elements);
184 $userdata->UserOptionalFields($optionalfields);
187 $response->data($userdata);
194 $ils->acceptitem($request);
196 Processes an AcceptItem request.
204 # Check our session and login if necessary.
205 $self->login() unless ($self->checkauth());
207 # Common preparation.
208 my $message = $self->parse_request_type($request);
209 my $response = NCIP::Response->new({type => $message . 'Response'});
210 $response->header($self->make_header($request));
212 # We only accept holds for the time being.
213 if ($request->{$message}->{RequestedActionType} =~ /^hold\W/i) {
214 # We need the item id or we can't do anything at all.
215 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
216 if (ref($item_barcode) eq 'NCIP::Problem') {
217 $response->problem($item_barcode);
221 # We need to find a patron barcode or we can't look anyone up
223 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request, 'UserIdentifierValue');
224 if (ref($user_barcode) eq 'NCIP::Problem') {
225 $response->problem($user_barcode);
228 # Look up our patron by barcode:
229 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
230 if (ref($user) eq 'NCIP::Problem') {
231 $response->problem($user);
234 # We're doing patron checks before looking for bibliographic
235 # information and creating the item because problems with the
236 # patron are more likely to occur.
237 my $problem = $self->check_user_for_problems($user, 'HOLD');
239 $response->problem($problem);
243 # Check if the item barcode already exists:
244 my $item = $self->retrieve_copy_details_by_barcode($item_barcode);
246 # What to do here was not defined in the
247 # specification. Since the copies that we create this way
248 # should get deleted when checked in, it would be an error
249 # if we try to create another one. It means that something
250 # has gone wrong somewhere.
254 ProblemType => 'Duplicate Item',
255 ProblemDetail => "Item with barcode $item_barcode already exists.",
256 ProblemElement => $item_idfield,
257 ProblemValue => $item_barcode
264 # Now, we have to create our new copy and/or bib and call number.
266 # First, we have to gather the necessary information from the
267 # request. Store in a hashref for convenience. We may write a
268 # method to get this information in the future if we find we
269 # need it in other handlers. Such a function would be a
270 # candidate to go into our parent, NCIP::ILS.
272 barcode => $item_barcode,
273 call_number => $request->{$message}->{ItemOptionalFields}->{ItemDescription}->{CallNumber},
274 title => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Title},
275 author => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Author},
276 publisher => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Publisher},
277 publication_date => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{PublicationDate},
278 medium => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{MediumType},
279 electronic => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{ElectronicResource}
282 if ($self->{config}->{items}->{use_precats}) {
283 # We only need to create a precat copy.
284 $item = $self->create_precat_copy($item_info);
286 # We have to create a "partial" bib record, a call number and a copy.
287 $item = $self->create_fuller_copy($item_info);
290 # If we failed to create the copy, report a problem.
294 ProblemType => 'Temporary Processing Failure',
295 ProblemDetail => 'Failed to create the item in the system',
296 ProblemElement => $item_idfield,
297 ProblemValue => $item_barcode
303 # We try to find the pickup location in our database. It's OK
304 # if it does not exist, the user's home library will be used
306 my $location = $self->find_location_failover($request->{$message}->{PickupLocation}, $request, $message);
308 # Now, we place the hold on the newly created copy on behalf
309 # of the patron retrieved above.
310 my $hold = $self->place_hold($item, $user, $location);
311 if (ref($hold) eq 'NCIP::Problem') {
312 $response->problem($hold);
316 # We return the RequestId and optionally, the ItemID. We'll
317 # just return what was sent to us, since we ignored all of it
320 $data->{RequestId} = NCIP::RequestId->new(
322 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
323 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
324 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
327 $data->{ItemId} = NCIP::Item::Id->new(
329 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
330 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
331 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
334 $response->data($data);
337 my $problem = NCIP::Problem->new();
338 $problem->ProblemType('Unauthorized Combination Of Element Values For System');
339 $problem->ProblemDetail('We only support Hold For Pickup');
340 $problem->ProblemElement('RequestedActionType');
341 $problem->ProblemValue($request->{$message}->{RequestedActionType});
342 $response->problem($problem);
350 $response = $ils->checkinitem($request);
352 Checks the item in if we can find the barcode in the message. It
353 returns problems if it cannot find the item in the system or if the
354 item is not checked out.
356 It could definitely use some more brains at some point as it does not
357 fully support everything that the standard allows. It also does not
358 really check if the checkin succeeded or not.
366 # Check our session and login if necessary:
367 $self->login() unless ($self->checkauth());
370 my $message = $self->parse_request_type($request);
371 my $response = NCIP::Response->new({type => $message . 'Response'});
372 $response->header($self->make_header($request));
374 # We need the copy barcode from the message.
375 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
376 if (ref($item_barcode) eq 'NCIP::Problem') {
377 $response->problem($item_barcode);
381 # Retrieve the copy details.
382 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
384 # Return an Unknown Item problem unless we find the copy.
388 ProblemType => 'Unknown Item',
389 ProblemDetail => "Item with barcode $item_barcode is not known.",
390 ProblemElement => $item_idfield,
391 ProblemValue => $item_barcode
398 # Check if a UserId was provided. If so, this is the patron to
399 # whom the copy should be checked out.
401 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
402 # We ignore the problem, because the UserId is optional.
403 if (ref($user_barcode) ne 'NCIP::Problem') {
404 $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
405 # We don't ignore a problem here, however.
406 if (ref($user) eq 'NCIP::Problem') {
407 $response->problem($user);
413 my $copy = $details->{copy};
415 # Look for a circulation and examine its information:
416 my $circ = $details->{circ};
418 # Check the circ details to see if the copy is checked out and, if
419 # the patron was provided, that it is checked out to the patron in
420 # question. We also verify the copy ownership and circulation
422 my $problem = $self->check_circ_details($circ, $copy, $user);
424 # We need to fill in some information, however.
425 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
426 $problem->ProblemValue($user_barcode);
427 $problem->ProblemElement($user_idfield);
428 } elsif (!$problem->ProblemElement()) {
429 $problem->ProblemElement($item_idfield);
431 $response->problem($problem);
435 # Checkin parameters. We want to skip hold targeting or making
436 # transits, to force the checkin despite the copy status, as
437 # well as void overdues.
439 copy_barcode => $copy->barcode(),
444 my $result = $U->simplereq(
446 'open-ils.circ.checkin.override',
447 $self->{session}->{authtoken},
450 if (ref($result) eq 'ARRAY') {
451 $result = $result->[0];
453 if ($result->{textcode} eq 'SUCCESS') {
454 # Delete the copy. Since delete_copy checks ownership
455 # before attempting to delete the copy, we don't bother
456 # checking who owns it.
457 $self->delete_copy($copy);
458 # We need the circulation user for the information below, so we retrieve it.
459 my $circ_user = $self->retrieve_user_by_id($circ->usr());
461 ItemId => NCIP::Item::Id->new(
463 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
464 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
465 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
468 UserId => NCIP::User::Id->new(
470 UserIdentifierType => 'Barcode Id',
471 UserIdentifierValue => $circ_user->card->barcode()
476 # Look for UserElements requested and add it to the response:
477 my $elements = $request->{$message}->{UserElementType};
479 $elements = [$elements] unless (ref $elements eq 'ARRAY');
480 my $optionalfields = $self->handle_user_elements($circ_user, $elements);
481 $data->{UserOptionalFields} = $optionalfields;
483 $elements = $request->{$message}->{ItemElementType};
485 $elements = [$elements] unless (ref $elements eq 'ARRAY');
486 my $optionalfields = $self->handle_item_elements($copy, $elements);
487 $data->{ItemOptionalFields} = $optionalfields;
490 $response->data($data);
492 # At some point in the future, we should probably check if
493 # they requested optional user or item elements and return
494 # those. For the time being, we ignore those at the risk of
495 # being considered non-compliant.
497 $response->problem(_problem_from_event('Checkin Failed', $result));
505 $response = $ils->renewitem($request);
507 Handle the RenewItem message.
515 # Check our session and login if necessary:
516 $self->login() unless ($self->checkauth());
519 my $message = $self->parse_request_type($request);
520 my $response = NCIP::Response->new({type => $message . 'Response'});
521 $response->header($self->make_header($request));
523 # We need the copy barcode from the message.
524 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
525 if (ref($item_barcode) eq 'NCIP::Problem') {
526 $response->problem($item_barcode);
530 # Retrieve the copy details.
531 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
533 # Return an Unknown Item problem unless we find the copy.
537 ProblemType => 'Unknown Item',
538 ProblemDetail => "Item with barcode $item_barcode is not known.",
539 ProblemElement => $item_idfield,
540 ProblemValue => $item_barcode
547 # User is required for RenewItem.
548 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
549 if (ref($user_barcode) eq 'NCIP::Problem') {
550 $response->problem($user_barcode);
553 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
554 if (ref($user) eq 'NCIP::Problem') {
555 $response->problem($user);
560 my $copy = $details->{copy};
562 # Look for a circulation and examine its information:
563 my $circ = $details->{circ};
565 # Check the circ details to see if the copy is checked out and, if
566 # the patron was provided, that it is checked out to the patron in
567 # question. We also verify the copy ownership and circulation
569 my $problem = $self->check_circ_details($circ, $copy, $user);
571 # We need to fill in some information, however.
572 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
573 $problem->ProblemValue($user_barcode);
574 $problem->ProblemElement($user_idfield);
575 } elsif (!$problem->ProblemElement()) {
576 $problem->ProblemElement($item_idfield);
578 $response->problem($problem);
582 # Check if user is blocked from renewals:
583 $problem = $self->check_user_for_problems($user, 'RENEW');
585 # Replace the ProblemElement and ProblemValue fields.
586 $problem->ProblemElement($user_idfield);
587 $problem->ProblemValue($user_barcode);
588 $response->problem($problem);
592 # Check if the duration rule allows renewals. It should have been
593 # fleshed during the copy details retrieve.
594 my $rule = $circ->duration_rule();
595 unless (ref($rule)) {
596 $rule = $U->simplereq(
598 'open-ils.pcrud.retrieve.crcd',
599 $self->{session}->{authtoken},
603 if ($rule->max_renewals() < 1) {
607 ProblemType => 'Item Not Renewable',
608 ProblemDetail => 'Item may not be renewed.',
609 ProblemElement => $item_idfield,
610 ProblemValue => $item_barcode
617 # Check if there are renewals remaining on the latest circ:
618 if ($circ->renewal_remaining() < 1) {
622 ProblemType => 'Maximum Renewals Exceeded',
623 ProblemDetail => 'Renewal cannot proceed because the User has already renewed the Item the maximum number of times permitted.',
624 ProblemElement => $item_idfield,
625 ProblemValue => $item_barcode
632 # Now, we attempt the renewal. If it fails, we simply say that the
633 # user is not allowed to renew this item, without getting into
636 copy_id => $copy->id(),
637 patron_id => $user->id(),
640 my $r = $U->simplereq(
642 'open-ils.circ.renew.override',
643 $self->{session}->{authtoken},
647 # We only look at the first one, since more than one usually means
649 if (ref($r) eq 'ARRAY') {
652 if ($r->{textcode} ne 'SUCCESS') {
653 $problem = _problem_from_event('Renewal Failed', $r);
654 $response->problem($problem);
657 ItemId => NCIP::Item::Id->new(
659 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
660 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
661 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
664 UserId => NCIP::User::Id->new(
666 UserIdentifierType => 'Barcode Id',
667 UserIdentifierValue => $user->card->barcode()
671 # We need to retrieve the copy details again to refresh our
672 # circ information to get the new due date.
673 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
674 $circ = $details->{circ};
675 $data->{DateDue} = _fix_date($circ->due_date());
677 # Look for UserElements requested and add it to the response:
678 my $elements = $request->{$message}->{UserElementType};
680 $elements = [$elements] unless (ref $elements eq 'ARRAY');
681 my $optionalfields = $self->handle_user_elements($user, $elements);
682 $data->{UserOptionalFields} = $optionalfields;
684 $elements = $request->{$message}->{ItemElementType};
686 $elements = [$elements] unless (ref $elements eq 'ARRAY');
687 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
688 $data->{ItemOptionalFields} = $optionalfields;
691 $response->data($data);
694 # At some point in the future, we should probably check if
695 # they requested optional user or item elements and return
696 # those. For the time being, we ignore those at the risk of
697 # being considered non-compliant.
704 $response = $ils->checkoutitem($request);
706 Handle the Checkoutitem message.
714 # Check our session and login if necessary:
715 $self->login() unless ($self->checkauth());
718 my $message = $self->parse_request_type($request);
719 my $response = NCIP::Response->new({type => $message . 'Response'});
720 $response->header($self->make_header($request));
722 # We need the copy barcode from the message.
723 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
724 if (ref($item_barcode) eq 'NCIP::Problem') {
725 $response->problem($item_barcode);
729 # Retrieve the copy details.
730 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
732 # Return an Unknown Item problem unless we find the copy.
736 ProblemType => 'Unknown Item',
737 ProblemDetail => "Item with barcode $item_barcode is not known.",
738 ProblemElement => $item_idfield,
739 ProblemValue => $item_barcode
746 # User is required for CheckOutItem.
747 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
748 if (ref($user_barcode) eq 'NCIP::Problem') {
749 $response->problem($user_barcode);
752 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
753 if (ref($user) eq 'NCIP::Problem') {
754 $response->problem($user);
759 my $copy = $details->{copy};
761 # Check if the copy can circulate.
762 unless ($self->copy_can_circulate($copy)) {
766 ProblemType => 'Item Does Not Circulate',
767 ProblemDetail => "Item with barcode $item_barcode does not circulate.",
768 ProblemElement => $item_idfield,
769 ProblemValue => $item_barcode
776 # Look for a circulation and examine its information:
777 my $circ = $details->{circ};
779 # Check if the item is already checked out.
780 if ($circ && !$circ->checkin_time()) {
784 ProblemType => 'Item Already Checked Out',
785 ProblemDetail => "Item with barcode $item_barcode is already checked out.",
786 ProblemElement => $item_idfield,
787 ProblemValue => $item_barcode
794 # Check if user is blocked from circulation:
795 my $problem = $self->check_user_for_problems($user, 'CIRC');
797 # Replace the ProblemElement and ProblemValue fields.
798 $problem->ProblemElement($user_idfield);
799 $problem->ProblemValue($user_barcode);
800 $response->problem($problem);
804 # Now, we attempt the check out. If it fails, we simply say that
805 # the user is not allowed to check out this item, without getting
808 copy_id => $copy->id(),
809 patron_id => $user->id(),
811 my $r = $U->simplereq(
813 'open-ils.circ.checkout.full.override',
814 $self->{session}->{authtoken},
818 # We only look at the first one, since more than one usually means
820 if (ref($r) eq 'ARRAY') {
823 if ($r->{textcode} ne 'SUCCESS') {
824 $problem = _problem_from_event('Check Out Failed', $r);
825 $response->problem($problem);
828 ItemId => NCIP::Item::Id->new(
830 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
831 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
832 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
835 UserId => NCIP::User::Id->new(
837 UserIdentifierType => 'Barcode Id',
838 UserIdentifierValue => $user->card->barcode()
842 # We need to retrieve the copy details again to refresh our
843 # circ information to get the due date.
844 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
845 $circ = $details->{circ};
846 $data->{DateDue} = _fix_date($circ->due_date());
848 # Look for UserElements requested and add it to the response:
849 my $elements = $request->{$message}->{UserElementType};
851 $elements = [$elements] unless (ref $elements eq 'ARRAY');
852 my $optionalfields = $self->handle_user_elements($user, $elements);
853 $data->{UserOptionalFields} = $optionalfields;
855 $elements = $request->{$message}->{ItemElementType};
857 $elements = [$elements] unless (ref $elements eq 'ARRAY');
858 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
859 $data->{ItemOptionalFields} = $optionalfields;
862 $response->data($data);
865 # At some point in the future, we should probably check if
866 # they requested optional user or item elements and return
867 # those. For the time being, we ignore those at the risk of
868 # being considered non-compliant.
875 $response = $ils->requestitem($request);
877 Handle the NCIP RequestItem message.
884 # Check our session and login if necessary:
885 $self->login() unless ($self->checkauth());
888 my $message = $self->parse_request_type($request);
889 my $response = NCIP::Response->new({type => $message . 'Response'});
890 $response->header($self->make_header($request));
892 # Because we need to have a user to place a hold, because the user
893 # is likely to have problems, and because getting the item
894 # information for the hold is trickier than getting the user
895 # information, we'll do the user first and short circuit out of
896 # the function if there is a problem with the user.
897 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
898 if (ref($user_barcode) eq 'NCIP::Problem') {
899 $response->problem($user_barcode);
902 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
903 if (ref($user) eq 'NCIP::Problem') {
904 $response->problem($user);
907 my $problem = $self->check_user_for_problems($user, 'HOLD');
909 $response->problem($problem);
913 # RequestItem is a blast. We need to check if we have a copy
914 # barcode and/or if we have BibliographicIds. If we have both or
915 # either, we then need to figure out what we're placing the hold
916 # on, a copy, a volume or a bib. We don't currently do part holds,
917 # but maybe we should some day. We can also be sent more than 1
918 # BibliographicId, so we look for certain identifiers first, and
919 # then others in decreasing preference: SYSNUMBER, ISBN, and ISSN.
921 # Not to mention that there are two kinds of BibliographicId field
922 # with different field names, and both can be intermixed in an
923 # incoming message! (I just /love/ this nonsense.)
925 # This here is the thing we're going to put on hold:
928 # We need copy details if we find in a couple of places below.
931 # We need the copy barcode from the message.
932 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
933 if (ref($item_barcode) ne 'NCIP::Problem') {
934 # Retrieve the copy details.
935 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
936 unless ($copy_details) {
937 # Return an Unknown Item problem unless we find the copy.
941 ProblemType => 'Unknown Item',
942 ProblemDetail => "Item with barcode $item_barcode is not known.",
943 ProblemElement => $item_idfield,
944 ProblemValue => $item_barcode
950 $item = $copy_details->{volume}; # We place a volume hold.
953 # We weren't given copy information to target, or we can't find
954 # it, so we need to look for a target via BibliographicId.
956 my @biblio_ids = $self->find_bibliographic_ids($request);
958 $item = $self->find_target_via_bibliographic_id(@biblio_ids);
962 # If we don't have an item, then blow up with a problem that may
963 # have been set when we went looking for the ItemId.
965 if (ref($item_barcode) eq 'NCIP::Problem') {
966 $response->problem($item_barcode);
971 ProblemType => 'Request Item Not Found',
972 ProblemDetail => 'Unable to determine the item to request from input message.',
973 ProblemElement => 'NULL',
974 ProblemValue => 'NULL'
980 } elsif (ref($item) eq 'NCIP::Problem') {
981 $response->problem($item);
985 # We have an item. If we have a biblio.record_entry object,
986 # Auto-Graphics expects us to place the hold such that it is
987 # limited to the branch or system whose id they have given us.
988 # We, therefore, look for an org_unit based on the ToAgencyId from
989 # the InitiationHeader.
991 if (ref($item) eq 'Fieldmapper::biblio::record_entry') {
992 $ou = $self->find_location_failover(undef, $request, $message);
995 # See if we were given a PickupLocation.
997 if ($request->{$message}->{PickupLocation}) {
998 my $loc = $request->{$message}->{PickupLocation};
999 $loc =~ s/^.*://; # strip everything up to the last
1000 # semi-colon, if any.
1001 $location = $self->retrieve_org_unit_by_shortname($loc);
1004 # Look for a NeedBeforeDate to use as expiration...
1005 my $hold_expiration = $request->{$message}->{NeedBeforeDate};
1008 my $hold = $self->place_hold($item, $user, $location, $hold_expiration, $ou);
1009 if (ref($hold) eq 'NCIP::Problem') {
1010 $response->problem($hold);
1013 RequestId => NCIP::RequestId->new(
1015 RequestIdentifierType => 'SYSNUMBER',
1016 RequestIdentifierValue => $hold->id()
1019 UserId => NCIP::User::Id->new(
1021 UserIdentifierType => 'Barcode Id',
1022 UserIdentifierValue => $user->card->barcode()
1025 RequestType => $request->{$message}->{RequestType},
1026 RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1028 # Look for UserElements requested and add it to the response:
1029 my $elements = $request->{$message}->{UserElementType};
1031 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1032 my $optionalfields = $self->handle_user_elements($user, $elements);
1033 $data->{UserOptionalFields} = $optionalfields;
1035 $elements = $request->{$message}->{ItemElementType};
1037 $copy_details = $self->find_copy_details_by_item($item) unless ($copy_details);
1038 $elements = [$elements] unless (ref($elements) eq 'ARRAY');
1039 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1040 $data->{ItemOptionalFields} = $optionalfields;
1043 $response->data($data);
1049 =head2 cancelrequestitem
1051 $response = $ils->cancelrequestitem($request);
1053 Handle the NCIP CancelRequestItem message.
1057 sub cancelrequestitem {
1059 my $request = shift;
1060 # Check our session and login if necessary:
1061 $self->login() unless ($self->checkauth());
1064 my $message = $self->parse_request_type($request);
1065 my $response = NCIP::Response->new({type => $message . 'Response'});
1066 $response->header($self->make_header($request));
1068 # UserId is required by the standard, but we might not really need it.
1069 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1070 if (ref($user_barcode) eq 'NCIP::Problem') {
1071 $response->problem($user_barcode);
1074 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1075 if (ref($user) eq 'NCIP::Problem') {
1076 $response->problem($user);
1080 # See if we got a ItemId and a barcode:
1082 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1083 if (ref($item_barcode) ne 'NCIP::Problem') {
1084 # Retrieve the copy details.
1085 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1086 unless ($copy_details) {
1087 # Return an Unknown Item problem unless we find the copy.
1091 ProblemType => 'Unknown Item',
1092 ProblemDetail => "Item with barcode $item_barcode is not known.",
1093 ProblemElement => $item_idfield,
1094 ProblemValue => $item_barcode
1102 # See if we got a RequestId:
1104 if ($request->{$message}->{RequestId}) {
1105 $requestid = NCIP::RequestId->new(
1107 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1108 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1109 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1114 # Just a note: In the below, we cannot rely on the hold or transit
1115 # fields of the copy_details, even if we have retrieved it. This
1116 # is because that hold and transit may not be the ones that we're
1117 # looking for, i.e. they could be for another patron, etc.
1119 # See if we can find the hold:
1122 $hold = $U->simplereq(
1124 'open-ils.pcrud.retrieve.ahr',
1125 $self->{session}->{authtoken},
1126 $requestid->{RequestIdentifierValue},
1127 {flesh => 1, flesh_fields => {ahr => ['transit']}}
1130 # Report a problem that we couldn't find a hold by that id.
1134 ProblemType => 'Unknown Request',
1135 ProblemDetail => 'No request with this identifier found',
1136 ProblemElement => 'RequestIdentifierValue',
1137 ProblemValue => $requestid->{RequestIdentifierValue}
1141 } elsif ($hold->cancel_time()) {
1145 ProblemType => 'Request Already Canceled',
1146 ProblemDetail => 'Request has already been canceled',
1147 ProblemElement => 'RequestIdentifierValue',
1148 ProblemValue => $requestid->{RequestIdentifierValue}
1152 } elsif ($hold->transit()) {
1156 ProblemType => 'Request Already Processed',
1157 ProblemDetail => 'Request has already been processed',
1158 ProblemElement => 'RequestIdentifierValue',
1159 ProblemValue => $requestid->{RequestIdentifierValue}
1163 } elsif ($hold->usr() == $user->id()) {
1164 # Check the target matches the copy information, if any,
1165 # that we were given.
1167 if ($copy_details) {
1168 if ($hold->hold_type() eq 'V') {
1169 $obj_id = $copy_details->{volume}->id();
1170 } elsif ($hold->hold_type() eq 'T') {
1171 $obj_id = $copy_details->{mvr}->doc_id();
1172 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1173 $obj_id = $copy_details->{copy}->id();
1176 if ($obj_id && $hold->target() != $obj_id) {
1180 ProblemType => 'Request Not For This Item',
1181 ProblemDetail => "Request is not for this item",
1182 ProblemElement => $item_idfield,
1183 ProblemElement => $item_barcode
1188 $self->cancel_hold($hold);
1190 RequestId => $requestid,
1191 UserId => NCIP::User::Id->new(
1193 UserIdentifierType => 'Barcode Id',
1194 UserIdentifierValue => $user->card->barcode()
1198 # Look for UserElements requested and add it to the response:
1199 my $elements = $request->{$message}->{UserElementType};
1201 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1202 my $optionalfields = $self->handle_user_elements($user, $elements);
1203 $data->{UserOptionalFields} = $optionalfields;
1205 $elements = $request->{$message}->{ItemElementType};
1206 if ($elements && $copy_details) {
1207 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1208 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1209 $data->{ItemOptionalFields} = $optionalfields;
1211 $response->data($data);
1214 # Report a problem that the hold is not for this user.
1218 ProblemType => 'Request Not For This User',
1219 ProblemDetail => 'Request is not for this user.',
1220 ProblemElement => $user_idfield,
1221 ProblemValue => $user_barcode
1227 # At this point, we *must have* an ItemId and therefore
1228 # $copy_details, so return the problem from looking up the
1229 # barcode if we don't have $copy_details.
1230 if (!$copy_details) {
1231 $response->problem($item_barcode);
1233 # We have to search for the hold based on the copy details and
1234 # the user. We'll need to search for copy (or force) holds, a
1235 # volume hold, or a title hold.
1236 $hold = $self->_hold_search($user, $copy_details);
1237 if ($hold && $hold->transit()) {
1241 ProblemType => 'Request Already Processed',
1242 ProblemDetail => 'Request has already been processed',
1243 ProblemElement => 'RequestIdentifierValue',
1244 ProblemValue => $requestid->{RequestIdentifierValue}
1249 $self->cancel_hold($hold);
1251 RequestId => NCIP::RequestId->new(
1253 RequestIdentifierType => 'SYSNUMBER',
1254 RequestIdentifierValue => $hold->id()
1257 UserId => NCIP::User::Id->new(
1259 UserIdentifierType => 'Barcode Id',
1260 UserIdentifierValue => $user->card->barcode()
1264 # Look for UserElements requested and add it to the response:
1265 my $elements = $request->{$message}->{UserElementType};
1267 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1268 my $optionalfields = $self->handle_user_elements($user, $elements);
1269 $data->{UserOptionalFields} = $optionalfields;
1271 $elements = $request->{$message}->{ItemElementType};
1272 if ($elements && $copy_details) {
1273 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1274 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1275 $data->{ItemOptionalFields} = $optionalfields;
1277 $response->data($data);
1282 ProblemType => 'Unknown Request',
1283 ProblemDetail => 'No request found for the item and user',
1284 ProblemElement => 'NULL',
1285 ProblemValue => 'NULL'
1296 =head1 METHODS USEFUL to SUBCLASSES
1298 =head2 handle_user_elements
1299 $useroptionalfield = $ils->handle_user_elements($user, $elements);
1301 Returns NCIP::User::OptionalFields for the given user and arrayref of
1306 sub handle_user_elements {
1309 my $elements = shift;
1310 my $optionalfields = NCIP::User::OptionalFields->new();
1312 # First, we'll look for name information.
1313 if (grep {$_ eq 'Name Information'} @$elements) {
1314 my $name = NCIP::StructuredPersonalUserName->new();
1315 $name->Surname($user->family_name());
1316 $name->GivenName($user->first_given_name());
1317 $name->Prefix($user->prefix());
1318 $name->Suffix($user->suffix());
1319 $optionalfields->NameInformation($name);
1322 # Next, check for user address information.
1323 if (grep {$_ eq 'User Address Information'} @$elements) {
1326 # See if the user has any valid, physcial addresses.
1327 foreach my $addr (@{$user->addresses()}) {
1328 next if ($U->is_true($addr->pending()));
1329 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
1330 my $structured = NCIP::StructuredAddress->new();
1331 $structured->Line1($addr->street1());
1332 $structured->Line2($addr->street2());
1333 $structured->Locality($addr->city());
1334 $structured->Region($addr->state());
1335 $structured->PostalCode($addr->post_code());
1336 $structured->Country($addr->country());
1337 $address->PhysicalAddress(
1338 NCIP::PhysicalAddress->new(
1340 StructuredAddress => $structured,
1341 Type => 'Postal Address'
1345 push @$addresses, $address;
1348 # Right now, we're only sharing email address if the user
1350 if ($user->email()) {
1351 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
1352 $address->ElectronicAddress(
1353 NCIP::ElectronicAddress->new({
1355 Data=>$user->email()
1358 push @$addresses, $address;
1360 # Auto-graphics asked for the phone numbers.
1361 if ($user->day_phone()) {
1362 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Day Phone'});
1363 $address->ElectronicAddress(
1364 NCIP::ElectronicAddress->new(
1367 Data=>$user->day_phone()
1371 push @$addresses, $address;
1373 if ($user->evening_phone()) {
1374 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Evening Phone'});
1375 $address->ElectronicAddress(
1376 NCIP::ElectronicAddress->new(
1378 Type=>'Evening Phone',
1379 Data=>$user->evening_phone()
1383 push @$addresses, $address;
1385 if ($user->other_phone()) {
1386 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Other Phone'});
1387 $address->ElectronicAddress(
1388 NCIP::ElectronicAddress->new(
1390 Type=>'Other Phone',
1391 Data=>$user->other_phone()
1395 push @$addresses, $address;
1398 $optionalfields->UserAddressInformation($addresses);
1401 # Check for User Privilege.
1402 if (grep {$_ eq 'User Privilege'} @$elements) {
1403 # Get the user's group:
1404 my $pgt = $U->simplereq(
1406 'open-ils.pcrud.retrieve.pgt',
1407 $self->{session}->{authtoken},
1411 my $privilege = NCIP::User::Privilege->new();
1412 $privilege->AgencyId($user->home_ou->shortname());
1413 $privilege->AgencyUserPrivilegeType($pgt->name());
1414 $privilege->ValidToDate(_fix_date($user->expire_date()));
1415 $privilege->ValidFromDate(_fix_date($user->create_date()));
1417 my $status = 'Active';
1418 if (_expired($user)) {
1419 $status = 'Expired';
1420 } elsif ($U->is_true($user->barred())) {
1422 } elsif (!$U->is_true($user->active())) {
1423 $status = 'Inactive';
1426 $privilege->UserPrivilegeStatus(
1427 NCIP::User::PrivilegeStatus->new({
1428 UserPrivilegeStatusType => $status
1433 $optionalfields->UserPrivilege([$privilege]);
1437 # Check for Block Or Trap.
1438 if (grep {$_ eq 'Block Or Trap'} @$elements) {
1441 # First, let's check if the profile is blocked from ILL.
1442 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1443 my $block = NCIP::User::BlockOrTrap->new();
1444 $block->AgencyId($user->home_ou->shortname());
1445 $block->BlockOrTrapType('Block Interlibrary Loan');
1446 push @$blocks, $block;
1449 # Next, we loop through the user's standing penalties
1450 # looking for blocks on CIRC, HOLD, and RENEW.
1451 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
1452 foreach my $penalty (@{$user->standing_penalties()}) {
1453 next unless($penalty->standing_penalty->block_list());
1454 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
1455 my $ou = $U->simplereq(
1457 'open-ils.pcrud.retrieve.aou',
1458 $self->{session}->{authtoken},
1459 $penalty->org_unit()
1463 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
1464 my $bot = NCIP::User::BlockOrTrap->new();
1465 $bot->AgencyId($ou->shortname());
1466 $bot->BlockOrTrapType('Block Checkout');
1467 push @$blocks, $bot;
1472 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
1473 my $bot = NCIP::User::BlockOrTrap->new();
1474 $bot->AgencyId($ou->shortname());
1475 $bot->BlockOrTrapType('Block Holds');
1476 push @$blocks, $bot;
1481 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
1482 my $bot = NCIP::User::BlockOrTrap->new();
1483 $bot->AgencyId($ou->shortname());
1484 $bot->BlockOrTrapType('Block Renewals');
1485 push @$blocks, $bot;
1489 # Stop after we report one of each, even if more
1491 last if ($have_circ && $have_renew && $have_hold);
1494 $optionalfields->BlockOrTrap($blocks);
1497 return $optionalfields;
1500 =head2 handle_item_elements
1504 sub handle_item_elements {
1507 my $elements = shift;
1508 my $optionalfields = NCIP::Item::OptionalFields->new();
1510 my $details; # In case we need for more than one.
1512 if (grep {$_ eq 'Bibliographic Description'} @$elements) {
1514 # Check for a precat copy, 'cause it is simple.
1515 if ($copy->dummy_title()) {
1516 $description = NCIP::Item::BibliographicDescription->new();
1517 $description->Title($copy->dummy_title());
1518 $description->Author($copy->dummy_author());
1519 if ($copy->dummy_isbn()) {
1520 $description->BibliographicItemId(
1521 NCIP::Item::BibliographicItemId->new(
1523 BibliographicItemIdentifier => $copy->dummy_isbn(),
1524 BibliographicItemIdentifierCode => 'ISBN'
1530 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1531 $description = NCIP::Item::BibliographicDescription->new();
1532 $description->Title($details->{mvr}->title());
1533 $description->Author($details->{mvr}->author());
1534 $description->BibliographicRecordId(
1535 NCIP::Item::BibliographicRecordId->new(
1537 BibliographicRecordIdentifier => $details->{mvr}->doc_id(),
1538 BibliographicRecordIdentifierCode => 'SYSNUMBER'
1542 if ($details->{mvr}->publisher()) {
1543 $description->Publisher($details->{mvr}->publisher());
1545 if ($details->{mvr}->pubdate()) {
1546 $description->PublicationDate($details->{mvr}->pubdate());
1548 if ($details->{mvr}->edition()) {
1549 $description->Edition($details->{mvr}->edition());
1552 $optionalfields->BibliographicDescription($description) if ($description);
1555 if (grep {$_ eq 'Item Description'} @$elements) {
1556 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1557 # Call Number is the only field we currently return. We also
1558 # do not attempt to retun a prefix and suffix. Someone else
1559 # can deal with that if they want it.
1560 if ($details->{volume}) {
1561 $optionalfields->ItemDescription(
1562 NCIP::Item::Description->new(
1563 {CallNumber => $details->{volume}->label()}
1569 if (grep {$_ eq 'Circulation Status'} @$elements) {
1570 my $status = $copy->status();
1571 $status = $self->retrieve_copy_status($status) unless (ref($status));
1572 $optionalfields->CirculationStatus($status->name()) if ($status);
1575 if (grep {$_ eq 'Date Due'} @$elements) {
1576 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1577 if ($details->{circ}) {
1578 if (!$details->{circ}->checkin_time()) {
1579 $optionalfields->DateDue(_fix_date($details->{circ}->due_date()));
1584 if (grep {$_ eq 'Item Use Restriction Type'} @$elements) {
1585 $optionalfields->ItemUseRestrictionType('None');
1588 if (grep {$_ eq 'Physical Condition'} @$elements) {
1589 $optionalfields->PhysicalCondition(
1590 NCIP::Item::PhysicalCondition->new(
1591 {PhysicalConditionType => 'Unknown'}
1596 return $optionalfields;
1603 Login to Evergreen via OpenSRF. It uses internal state from the
1604 configuration file to login.
1608 # Login via OpenSRF to Evergreen.
1612 # Get the authentication seed.
1613 my $seed = $U->simplereq(
1615 'open-ils.auth.authenticate.init',
1616 $self->{config}->{credentials}->{username}
1621 my $response = $U->simplereq(
1623 'open-ils.auth.authenticate.complete',
1625 username => $self->{config}->{credentials}->{username},
1626 password => md5_hex(
1627 $seed . md5_hex($self->{config}->{credentials}->{password})
1630 workstation => $self->{config}->{credentials}->{workstation}
1634 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1635 $self->{session}->{authtime} = $response->{payload}->{authtime};
1637 # Set/reset the work_ou and user data in case something changed.
1639 # Retrieve the work_ou as an object.
1640 $self->{session}->{work_ou} = $U->simplereq(
1642 'open-ils.pcrud.search.aou',
1643 $self->{session}->{authtoken},
1644 {shortname => $self->{config}->{credentials}->{work_ou}}
1647 # We need the user information in order to do some things.
1648 $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1656 $valid = $ils->checkauth();
1658 Returns 1 if the object a 'valid' authtoken, 0 if not.
1665 # We use AppUtils to do the heavy lifting.
1666 if (defined($self->{session})) {
1667 if ($U->check_user_session($self->{session}->{authtoken})) {
1674 # If we reach here, we don't have a session, so we are definitely
1679 =head2 retrieve_user_by_barcode
1681 $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1683 Do a fleshed retrieve of a patron by barcode. Return the patron if
1684 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1686 The id field argument is used for the ProblemElement field in the
1687 NCIP::Problem object.
1689 An invalid patron is one where the barcode is not found in the
1690 database, the patron is deleted, or the barcode used to retrieve the
1691 patron is not active. The problem element is also returned if an error
1692 occurs during the retrieval.
1696 sub retrieve_user_by_barcode {
1697 my ($self, $barcode, $idfield) = @_;
1698 my $result = $U->simplereq(
1700 'open-ils.actor.user.fleshed.retrieve_by_barcode',
1701 $self->{session}->{authtoken},
1706 # Check for a failure, or a deleted, inactive, or expired user,
1707 # and if so, return empty userdata.
1708 if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1709 || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1711 my $problem = NCIP::Problem->new();
1712 $problem->ProblemType('Unknown User');
1713 $problem->ProblemDetail("User with barcode $barcode unknown");
1714 $problem->ProblemElement($idfield);
1715 $problem->ProblemValue($barcode);
1722 =head2 retrieve_user_by_id
1724 $user = $ils->retrieve_user_by_id($id);
1726 Similar to C<retrieve_user_by_barcode> but takes the user's database
1727 id rather than barcode. This is useful when you have a circulation or
1728 hold and need to get information about the user's involved in the hold
1731 It returns a fleshed user on success or undef on failure.
1735 sub retrieve_user_by_id {
1736 my ($self, $id) = @_;
1738 # Do a fleshed retrieve of the patron, and flesh the fields that
1739 # we would normally use.
1740 my $result = $U->simplereq(
1742 'open-ils.actor.user.fleshed.retrieve',
1743 $self->{session}->{authtoken},
1745 [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1747 # Check for an error.
1748 undef($result) if ($result && $U->event_code($result));
1753 =head2 check_user_for_problems
1755 $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1757 This function checks if a user has a blocked profile or any from a
1758 list of provided blocks. If it does, then a NCIP::Problem object is
1759 returned, otherwise an undefined value is returned.
1761 The list of blocks appears as additional arguments after the user. You
1762 can provide any value(s) that might appear in a standing penalty block
1763 lit in Evergreen. The example above checks for HOLD, CIRC, and
1764 RENEW. Any number of such values can be provided. If none are
1765 provided, the function only checks if the patron's profiles appears in
1766 the object's blocked profiles list.
1768 It stops on the first matching block, if any.
1772 sub check_user_for_problems {
1777 # Fill this in if we have a problem, otherwise just return it.
1780 # First, check the user's profile.
1781 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1782 $problem = NCIP::Problem->new(
1784 ProblemType => 'User Blocked',
1785 ProblemDetail => 'User blocked from inter-library loan',
1786 ProblemElement => 'NULL',
1787 ProblemValue => 'NULL'
1792 # Next, check if the patron has one of the indicated blocks.
1794 foreach my $penalty (@{$user->standing_penalties()}) {
1795 if ($penalty->standing_penalty->block_list()) {
1796 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1797 foreach my $block (@blocks) {
1798 if (grep {$_ =~ /$block/} @pblocks) {
1799 $problem = NCIP::Problem->new(
1801 ProblemType => 'User Blocked',
1802 ProblemDetail => 'User blocked from ' .
1803 ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1804 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1805 ProblemElement => 'NULL',
1806 ProblemValue => 'NULL'
1820 =head2 check_circ_details
1822 $problem = $ils->check_circ_details($circ, $copy, $user);
1824 Checks if we can checkin or renew a circulation. That is, the
1825 circulation is still open (i.e. the copy is still checked out), if we
1826 either own the copy or are the circulation location, and if the
1827 circulation is for the optional $user argument. $circ and $copy are
1828 required. $user is optional.
1830 Returns a problem if any of the above conditions fail. Returns undef
1831 if they pass and we can proceed with the checkin or renewal.
1833 If the failure occurred on the copy-related checks, then the
1834 ProblemElement field will be undefined and needs to be filled in with
1835 the item id field name. If the check for the copy being checked out to
1836 the provided user fails, then both ProblemElement and ProblemValue
1837 fields will be empty and need to be filled in by the caller.
1841 sub check_circ_details {
1842 my ($self, $circ, $copy, $user) = @_;
1844 # Shortcut for the next check.
1845 my $ou_id = $self->{session}->{work_ou}->id();
1847 if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1848 # Item isn't checked out.
1849 return NCIP::Problem->new(
1851 ProblemType => 'Item Not Checked Out',
1852 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1853 ProblemValue => $copy->barcode()
1857 # Get data on the patron who has it checked out.
1858 my $circ_user = $self->retrieve_user_by_id($circ->usr());
1859 if ($user && $circ_user && $user->id() != $circ_user->id()) {
1860 # The ProblemElement and ProblemValue field need to be
1861 # filled in by the caller.
1862 return NCIP::Problem->new(
1864 ProblemType => 'Item Not Checked Out To This User',
1865 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1870 # If we get here, we're good to go.
1874 =head2 retrieve_copy_details_by_barcode
1876 $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1878 Look up and retrieve some copy details by the copy barcode. This
1879 method returns either a hashref with the copy details or undefined if
1880 no copy exists with that barcode or if some error occurs.
1882 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1884 This method differs from C<retrieve_user_by_barcode> in that a copy
1885 cannot be invalid if it exists and it is not always an error if no
1886 copy exists. In some cases, when handling AcceptItem, we might prefer
1887 there to be no copy.
1891 sub retrieve_copy_details_by_barcode {
1893 my $barcode = shift;
1895 my $copy = $U->simplereq(
1897 'open-ils.circ.copy_details.retrieve.barcode',
1898 $self->{session}->{authtoken},
1902 # If $copy is an event, return undefined.
1903 if ($copy && $U->event_code($copy)) {
1910 =head2 find_copy_details_by_item
1912 $copy_details = $ils->find_copy_details_by_item($item);
1914 This routine returns a copy_details hashref (See:
1915 retrieve_copy_details_by_barcode) for a given item. It attempts to
1916 find the "first" copy for the given item. If item is a call number it
1917 looks for the first, not deleted copy. If item is a bib, it looks for
1918 the first not deleted copy on the first not deleted call number. If
1919 item is a copy, it simply returns the details for the copy.
1923 sub find_copy_details_by_item {
1929 if (ref($item) eq 'Fieldmapper::biblio::record_entry') {
1930 my $acns = $U->simplereq(
1932 'open-ils.pcrud.search.acn.atomic',
1933 $self->{session}->{authtoken},
1935 record => $item->id(),
1939 ($item) = sort {$a->id() <=> $b->id()} @{$acns};
1942 if (ref($item) eq 'Fieldmapper::asset::call_number') {
1943 my $copies = $U->simplereq(
1945 'open-ils.pcrud.search.acp.atomic',
1946 $self->{session}->{authtoken},
1948 call_number => $item->id(),
1952 ($item) = sort {$a->id() <=> $b->id()} @{$copies};
1955 if (ref($item) eq 'Fieldmapper::asset::copy') {
1956 $details = $self->retrieve_copy_details_by_barcode($item->barcode());
1962 =head2 retrieve_copy_status
1964 $status = $ils->retrieve_copy_status($id);
1966 Retrive a copy status object by database ID.
1970 sub retrieve_copy_status {
1974 my $status = $U->simplereq(
1976 'open-ils.pcrud.retrieve.ccs',
1977 $self->{session}->{authtoken},
1984 =head2 retrieve_org_unit_by_shortname
1986 $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1988 Retrieves an org. unit from the database by shortname, and fleshes the
1989 ou_type field. Returns the org. unit as a Fieldmapper object or
1994 sub retrieve_org_unit_by_shortname {
1996 my $shortname = shift;
1998 my $aou = $U->simplereq(
2000 'open-ils.actor.org_unit.retrieve_by_shortname',
2004 # We want to retrieve the type and manually "flesh" the object.
2006 my $type = $U->simplereq(
2008 'open-ils.pcrud.retrieve.aou',
2009 $self->{session}->{authtoken},
2012 $aou->ou_type($type) if ($type);
2018 =head2 retrieve_copy_location
2020 $location = $ils->retrieve_copy_location($location_id);
2022 Retrieve a copy location based on id.
2026 sub retrieve_copy_location {
2030 my $location = $U->simplereq(
2032 'open-ils.pcrud.retrieve.acpl',
2033 $self->{session}->{authtoken},
2040 =head2 retrieve_biblio_record_entry
2042 $bre = $ils->retrieve_biblio_record_entry($bre_id);
2044 Given a biblio.record_entry.id, this method retrieves a bre object.
2048 sub retrieve_biblio_record_entry {
2052 my $bre = $U->simplereq(
2054 'open-ils.pcrud.retrieve.bre',
2055 $self->{session}->{authtoken},
2062 =head2 create_precat_copy
2065 barcode => '312340123456789',
2066 author => 'Public, John Q.',
2067 title => 'Magnum Opus',
2068 call_number => '005.82',
2069 publisher => 'Brick House',
2070 publication_date => '2014'
2073 $item = $ils->create_precat_copy($item_info);
2076 Create a "precat" copy to use for the incoming item using a hashref of
2077 item information. At a minimum, the barcode, author and title fields
2078 need to be filled in. The other fields are ignored if provided.
2080 This method is called by the AcceptItem handler if the C<use_precats>
2081 configuration option is turned on.
2085 sub create_precat_copy {
2087 my $item_info = shift;
2089 my $item = Fieldmapper::asset::copy->new();
2090 $item->barcode($item_info->{barcode});
2091 $item->call_number(OILS_PRECAT_CALL_NUMBER);
2092 $item->dummy_title($item_info->{title});
2093 $item->dummy_author($item_info->{author});
2094 $item->circ_lib($self->{session}->{work_ou}->id());
2095 $item->circulate('t');
2096 $item->holdable('t');
2097 $item->opac_visible('f');
2098 $item->deleted('f');
2099 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2100 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2103 $item->editor($self->{session}->{user}->id());
2104 $item->creator($self->{session}->{user}->id());
2107 # Actually create it:
2109 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2112 $xact = $ses->request(
2113 'open-ils.pcrud.transaction.begin',
2114 $self->{session}->{authtoken}
2116 $item = $ses->request(
2117 'open-ils.pcrud.create.acp',
2118 $self->{session}->{authtoken},
2121 $xact = $ses->request(
2122 'open-ils.pcrud.transaction.commit',
2123 $self->{session}->{authtoken}
2131 'open-ils.pcrud.transaction.rollback',
2132 $self->{session}->{authtoken}
2142 =head2 create_fuller_copy
2145 barcode => '31234003456789',
2146 author => 'Public, John Q.',
2147 title => 'Magnum Opus',
2148 call_number => '005.82',
2149 publisher => 'Brick House',
2150 publication_date => '2014'
2153 $item = $ils->create_fuller_copy($item_info);
2155 Creates a skeletal bibliographic record, call number, and copy for the
2156 incoming item using a hashref with item information in it. At a
2157 minimum, the barcode, author, title, and call_number fields must be
2160 This method is used by the AcceptItem handler if the C<use_precats>
2161 configuration option is NOT set.
2165 sub create_fuller_copy {
2167 my $item_info = shift;
2171 # We do everything in one transaction, because it should be atomic.
2172 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2176 $xact = $ses->request(
2177 'open-ils.pcrud.transaction.begin',
2178 $self->{session}->{authtoken}
2185 # The rest depends on there being a transaction.
2188 # Create the MARC record.
2189 my $record = MARC::Record->new();
2190 $record->encoding('UTF-8');
2191 $record->leader('00881nam a2200193 4500');
2192 my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
2194 push(@fields, MARC::Field->new('005', $datespec));
2195 push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
2196 push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
2197 # Publisher is a little trickier:
2198 if ($item_info->{publisher}) {
2199 my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
2200 $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
2201 push(@fields, $pub);
2203 # We have no idea if the author is personal corporate or something else, so we use a 720.
2204 push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
2205 $record->append_fields(@fields);
2206 my $marc = clean_marc($record);
2208 # Create the bib object.
2209 my $bib = Fieldmapper::biblio::record_entry->new();
2210 $bib->creator($self->{session}->{user}->id());
2211 $bib->editor($self->{session}->{user}->id());
2212 $bib->source($self->{bib_source}->id());
2219 $bib = $ses->request(
2220 'open-ils.pcrud.create.bre',
2221 $self->{session}->{authtoken},
2229 'open-ils.pcrud.transaction.rollback',
2230 $self->{session}->{authtoken}
2235 # Create the call number
2238 $acn = Fieldmapper::asset::call_number->new();
2239 $acn->creator($self->{session}->{user}->id());
2240 $acn->editor($self->{session}->{user}->id());
2241 $acn->label($item_info->{call_number});
2242 $acn->record($bib->id());
2243 $acn->owning_lib($self->{session}->{work_ou}->id());
2248 $acn = $ses->request(
2249 'open-ils.pcrud.create.acn',
2250 $self->{session}->{authtoken},
2258 'open-ils.pcrud.transaction.rollback',
2259 $self->{session}->{authtoken}
2267 $item = Fieldmapper::asset::copy->new();
2268 $item->barcode($item_info->{barcode});
2269 $item->call_number($acn->id());
2270 $item->circ_lib($self->{session}->{work_ou}->id);
2271 $item->circulate('t');
2272 if ($self->{config}->{items}->{use_force_holds}) {
2273 $item->holdable('f');
2275 $item->holdable('t');
2277 $item->opac_visible('f');
2278 $item->deleted('f');
2279 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2280 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2283 $item->editor($self->{session}->{user}->id);
2284 $item->creator($self->{session}->{user}->id);
2288 $item = $ses->request(
2289 'open-ils.pcrud.create.acp',
2290 $self->{session}->{authtoken},
2294 # Cross our fingers and commit the work.
2295 $xact = $ses->request(
2296 'open-ils.pcrud.transaction.commit',
2297 $self->{session}->{authtoken}
2304 'open-ils.pcrud.transaction.rollback',
2305 $self->{session}->{authtoken}
2306 )->gather(1) if ($xact);
2312 # We need to disconnect our session.
2315 # Now, we handle our asset stat_cat entries.
2317 # It would be nice to do these in the above transaction, but
2318 # pcrud does not support the ascecm object, yet.
2319 foreach my $entry (@{$self->{stat_cat_entries}}) {
2320 my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2322 $map->stat_cat($entry->stat_cat());
2323 $map->stat_cat_entry($entry->id());
2324 $map->owning_copy($item->id());
2325 # We don't really worry if it succeeds or not.
2328 'open-ils.circ.stat_cat.asset.copy_map.create',
2329 $self->{session}->{authtoken},
2340 $hold = $ils->place_hold($item, $user, $location, $expiration, $org_unit);
2342 This function places a hold on $item for $user for pickup at
2343 $location. If location is not provided or undefined, the user's home
2344 library is used as a fallback.
2346 The $expiration argument is optional and must be a properly formatted
2347 ISO date time. It will be used as the hold expire time, if
2348 provided. Otherwise the system default time will be used.
2350 The $org_unit parameter is only consulted in the event of $item being
2351 a biblio::record_entry object. In which case, it is expected to be
2352 undefined or an actor::org_unit object. If it is present, then its id
2353 and ou_type depth (if the ou_type field is fleshed) will be used to
2354 control the selection ou and selection depth for the hold. This
2355 essentially limits the hold to being filled by copies belonging to the
2356 specified org_unit or its children.
2358 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2359 (biblio::record_entry). The appropriate hold type will be placed
2360 depending on the object.
2362 On success, the method returns the object representing the hold. On
2363 failure, a NCIP::Problem object, describing the failure, is returned.
2371 my $location = shift;
2372 my $expiration = shift;
2373 my $org_unit = shift;
2375 # If $location is undefined, use the user's home_ou, which should
2376 # have been fleshed when the user was retrieved.
2377 $location = $user->home_ou() unless ($location);
2379 # $hold is the hold. $params is for the is_possible check.
2380 my ($hold, $params);
2382 # Prep the hold with fields common to all hold types:
2383 $hold = Fieldmapper::action::hold_request->new();
2384 $hold->isnew(1); # Just to make sure.
2385 $hold->target($item->id());
2386 $hold->usr($user->id());
2387 $hold->pickup_lib($location->id());
2388 $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2389 if (!$user->email()) {
2390 $hold->email_notify('f');
2391 $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2393 $hold->email_notify('t');
2397 $params = { pickup_lib => $location->id(), patronid => $user->id() };
2399 if (ref($item) eq 'Fieldmapper::asset::copy') {
2400 my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2401 $hold->hold_type($type);
2402 $hold->current_copy($item->id());
2403 $params->{hold_type} = $type;
2404 $params->{copy_id} = $item->id();
2405 } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2406 $hold->hold_type('V');
2407 $params->{hold_type} = 'V';
2408 $params->{volume_id} = $item->id();
2409 } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2410 $hold->hold_type('T');
2411 $params->{hold_type} = 'T';
2412 $params->{titleid} = $item->id();
2413 if ($org_unit && ref($org_unit) eq 'Fieldmapper::actor::org_unit') {
2414 $hold->selection_ou($org_unit->id());
2415 $hold->selection_depth($org_unit->ou_type->depth()) if (ref($org_unit->ou_type()));
2419 # Check for a duplicate hold:
2420 my $duplicate = $U->simplereq(
2422 'open-ils.pcrud.search.ahr',
2423 $self->{session}->{authtoken},
2425 hold_type => $hold->hold_type(),
2426 target => $hold->target(),
2427 usr => $hold->usr(),
2428 expire_time => {'>' => 'now'},
2429 cancel_time => undef,
2430 fulfillment_time => undef
2434 return NCIP::Problem->new(
2436 ProblemType => 'Duplicate Request',
2437 ProblemDetail => 'A request for this item already exists for this patron.',
2438 ProblemElement => 'NULL',
2439 ProblemValue => 'NULL'
2444 # Check if the hold is possible:
2445 my $r = $U->simplereq(
2447 'open-ils.circ.title_hold.is_possible',
2448 $self->{session}->{authtoken},
2452 if ($r->{success}) {
2453 $hold = $U->simplereq(
2455 'open-ils.circ.holds.create.override',
2456 $self->{session}->{authtoken},
2460 $hold = $hold->[0] if (ref($hold) eq 'ARRAY');
2461 $hold = _problem_from_event('Request Not Possible', $hold);
2463 # open-ils.circ.holds.create.override returns the id on
2464 # success, so we retrieve the full hold object from the
2465 # database to return it.
2466 $hold = $U->simplereq(
2468 'open-ils.pcrud.retrieve.ahr',
2469 $self->{session}->{authtoken},
2473 } elsif ($r->{last_event}) {
2474 $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2475 } elsif ($r->{textcode}) {
2476 $hold = _problem_from_event('Request Not Possible', $r);
2478 $hold = _problem_from_event('Request Not Possible');
2486 $ils->cancel_hold($hold);
2488 This method cancels the hold argument. It makes no checks on the hold,
2489 so if there are certain conditions that need to be fulfilled before
2490 the hold is canceled, then you must check them before calling this
2493 It returns undef on success or failure. If it fails, you've usually
2494 got bigger problems.
2502 my $r = $U->simplereq(
2504 'open-ils.circ.hold.cancel',
2505 $self->{session}->{authtoken},
2508 'Canceled via NCIPServer'
2516 $ils->delete_copy($copy);
2518 Deletes the copy, and if it is owned by our work_ou and not a precat,
2519 we also delete the volume and bib on which the copy depends.
2527 # Shortcut for ownership checks below.
2528 my $ou_id = $self->{session}->{work_ou}->id();
2530 # First, make sure the copy is not already deleted and we own it.
2531 return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2533 # Indicate we want to delete the copy.
2534 $copy->isdeleted(1);
2536 # Delete the copy using a backend call that will delete the copy,
2537 # the call number, and bib when appropriate.
2538 my $result = $U->simplereq(
2540 'open-ils.cat.asset.copy.fleshed.batch.update.override',
2541 $self->{session}->{authtoken},
2545 # We are currently not checking for succes or failure of the
2546 # above. At some point, someone may want to.
2551 =head2 copy_can_circulate
2553 $can_circulate = $ils->copy_can_circulate($copy);
2555 Check if the copy's location and the copy itself allow
2556 circulation. Return true if they do, and false if they do not.
2560 sub copy_can_circulate {
2564 my $location = $copy->location();
2565 unless (ref($location)) {
2566 $location = $self->retrieve_copy_location($location);
2569 return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2572 =head2 copy_can_fulfill
2574 $can_fulfill = $ils->copy_can_fulfill($copy);
2576 Check if the copy's location and the copy itself allow
2577 holds. Return true if they do, and false if they do not.
2581 sub copy_can_fulfill {
2585 my $location = $copy->location();
2586 unless (ref($location)) {
2587 $location = $self->retrieve_copy_location($location);
2590 return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2593 =head1 OVERRIDDEN PARENT METHODS
2595 =head2 find_user_barcode
2597 We dangerously override our parent's C<find_user_barcode> to return
2598 either the $barcode or a Problem object. In list context the barcode
2599 or problem will be the first argument and the id field, if any, will
2600 be the second. We also add a second, optional, argument to indicate a
2601 default value for the id field in the event of a failure to find
2602 anything at all. (Perl lets us get away with this.)
2606 sub find_user_barcode {
2608 my $request = shift;
2609 my $default = shift;
2612 my $message = $self->parse_request_type($request);
2613 if ($message eq 'LookupUser') {
2614 $default = 'AuthenticationInputData';
2616 $default = 'UserIdentifierValue';
2620 my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2623 $idfield = $default unless ($idfield);
2624 $value = NCIP::Problem->new();
2625 $value->ProblemType('Needed Data Missing');
2626 $value->ProblemDetail('Cannot find user barcode in message.');
2627 $value->ProblemElement($idfield);
2628 $value->ProblemValue('NULL');
2631 return (wantarray) ? ($value, $idfield) : $value;
2634 =head2 find_item_barcode
2636 We do pretty much the same thing as with C<find_user_barcode> for
2637 C<find_item_barcode>.
2641 sub find_item_barcode {
2643 my $request = shift;
2644 my $default = shift || 'ItemIdentifierValue';
2646 my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2649 $idfield = $default unless ($idfield);
2650 $value = NCIP::Problem->new();
2651 $value->ProblemType('Needed Data Missing');
2652 $value->ProblemDetail('Cannot find item barcode in message.');
2653 $value->ProblemElement($idfield);
2654 $value->ProblemValue('NULL');
2657 return (wantarray) ? ($value, $idfield) : $value;
2660 =head2 find_target_via_bibliographic_id
2662 $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2664 Searches for a bibliographic record to put on hold and returns an
2665 appropriate hold target item depending upon what it finds. If an
2666 appropriate, single target cannot be found, it returns an
2667 NCIP::Problem with the problem message.
2669 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2670 identifiers. If nothing is found, this method can return undef. (Gotta
2671 love Perl and untyped/weakly typed languages in general!)
2673 TODO: Figure out how to search OCLC numbers. We probably need to use
2674 "MARC Expert Search" if we don't want to do a JSON query on
2679 sub find_target_via_bibliographic_id {
2681 my @biblio_ids = @_;
2683 # The item that we find:
2686 # Id for our bib in Evergreen:
2689 # First, let's look for a SYSNUMBER:
2691 { ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'SYSNUMBER')
2692 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER')
2697 # BibliographicRecordId can have an AgencyId field if the
2698 # BibliographicRecordIdentifierCode is absent.
2699 if ($idobj->{AgencyId}) {
2700 $bibid = $idobj->{BibliographicRecordIdentifier};
2701 my $locname = $idobj->{AgencyId};
2703 $locname =~ s/^.*://;
2704 $loc = $self->retrieve_org_unit_by_shortname($locname);
2706 } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2707 $bibid = $idobj->{BibliographicRecordIdentifier};
2709 $bibid = $idobj->{BibliographicItemIdentifier};
2711 if ($bibid && $loc) {
2712 $item = $self->_call_number_search($bibid, $loc);
2714 $item = $U->simplereq(
2716 'open-ils.pcrud.retrieve.bre',
2717 $self->{session}->{authtoken},
2721 # Check if item is deleted so we'll look for more
2723 undef($item) if ($item && $U->is_true($item->deleted()));
2726 # Build an array of id objects based on the other identifier fields.
2729 ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISBN')
2730 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISBN')
2731 || ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISSN')
2732 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISSN')
2736 my $stashed_problem;
2737 # Reuse $idobj from above.
2738 foreach $idobj (@idobjs) {
2739 my ($idvalue, $idtype, $idfield);
2740 if ($_->{BibliographicItemIdentifier}) {
2741 $idvalue = $_->{BibliographicItemIdentifier};
2742 $idtype = $_->{BibliographicItemIdentifierCode};
2743 $idfield = 'BibliographicItemIdentifier';
2745 $idvalue = $_->{BibliographicRecordIdentifier};
2746 $idtype = $_->{BibliographicRecordIdentifierCode};
2747 $idfield = 'BibliographicRecordIdentifier';
2749 $item = $self->_bib_search($idvalue, $idtype);
2750 if (ref($item) eq 'NCIP::Problem') {
2751 $stashed_problem = $item unless($stashed_problem);
2752 $stashed_problem->ProblemElement($idfield);
2757 $item = $stashed_problem if (!$item && $stashed_problem);
2763 =head2 find_location_failover
2765 $location = $ils->find_location_failover($location, $request, $message);
2767 Attempts to retrieve an org_unit by shortname from the passed in
2768 $location. If that fails, $request and $message are used to lookup
2769 the ToAgencyId/AgencyId field and that is used. Returns an org_unit
2770 as retrieved by retrieve_org_unit_by_shortname if successful and undef
2775 sub find_location_failover {
2776 my ($self, $location, $request, $message) = @_;
2777 if ($request && !$message) {
2778 $message = $self->parse_request_type($request);
2782 # Because Auto-Graphics. (This should be configured somehow.)
2783 $location =~ s/^[^-]+-//;
2784 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2786 if ($request && $message && !$org_unit) {
2787 $location = $request->{$message}->{InitiationHeader}->{ToAgencyId}->{AgencyId};
2789 # Because Auto-Graphics. (This should be configured somehow.)
2790 $location =~ s/^[^-]+-//;
2791 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2798 # private subroutines not meant to be used directly by subclasses.
2799 # Most have to do with setup and/or state checking of implementation
2802 # Find, load, and parse our configuration file:
2806 # Find the configuration file via variables:
2807 my $file = OILS_NCIP_CONFIG_DEFAULT;
2808 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2810 $self->{config} = XMLin($file, NormaliseSpace => 2,
2811 ForceArray => ['block_profile', 'stat_cat_entry']);
2814 # Bootstrap OpenSRF::System and load the IDL.
2818 my $bootstrap_config = $self->{config}->{bootstrap};
2819 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2821 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2822 Fieldmapper->import(IDL => $idl);
2825 # Login and then initialize some object data based on the
2830 # Login to Evergreen.
2833 # Load the barred groups as pgt objects into a blocked_profiles
2835 $self->{blocked_profiles} = [];
2836 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2839 $pgt = $U->simplereq(
2841 'open-ils.pcrud.retrieve.pgt',
2842 $self->{session}->{authtoken},
2846 $pgt = $U->simplereq(
2848 'open-ils.pcrud.search.pgt',
2849 $self->{session}->{authtoken},
2853 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2856 # Load the bib source if we're not using precats.
2857 unless ($self->{config}->{items}->{use_precats}) {
2858 # Retrieve the default
2859 $self->{bib_source} = $U->simplereq(
2861 'open-ils.pcrud.retrieve.cbs',
2862 $self->{session}->{authtoken},
2863 BIB_SOURCE_DEFAULT);
2864 my $data = $self->{config}->{items}->{bib_source};
2866 $data = $data->[0] if (ref($data) eq 'ARRAY');
2869 $result = $U->simplereq(
2871 'open-ils.pcrud.retrieve.cbs',
2872 $self->{session}->{authtoken},
2876 $result = $U->simplereq(
2878 'open-ils.pcrud.search.cbs',
2879 $self->{session}->{authtoken},
2883 $self->{bib_source} = $result if ($result);
2887 # Load the required asset.stat_cat_entries:
2888 $self->{stat_cat_entries} = [];
2889 # First, make a regex for our ou and ancestors:
2890 my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2891 my $re = qr/(?:$ancestors)/;
2892 # Get the uniq stat_cat ids from the configuration:
2893 my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2894 # Retrieve all of the fleshed stat_cats and entries for the above.
2895 my $stat_cats = $U->simplereq(
2897 'open-ils.circ.stat_cat.asset.retrieve.batch',
2898 $self->{session}->{authtoken},
2901 foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2902 # Must have the stat_cat attr and the name, so we must have a
2904 next unless(ref $entry);
2905 my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2906 push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2910 # Search asset.call_number by a bre.id and location object. Return the
2911 # "closest" call_number if found, undef otherwise.
2912 sub _call_number_search {
2915 my $location = shift;
2917 # At some point, this should be smarter, and we should retrieve
2918 # ancestors and descendants and search with a JSON query or some
2919 # such with results ordered by proximity to the original location,
2920 # but I don't have time to implement that right now.
2921 my $acn = $U->simplereq(
2923 'open-ils.pcrud.search.acn',
2924 $self->{session}->{authtoken},
2925 {record => $bibid, owning_lib => $location->id()}
2931 # Do a multiclass.query to search for items by isbn or issn.
2934 my $idvalue = shift;
2938 my $result = $U->simplereq(
2940 'open-ils.search.biblio.multiclass',
2941 {searches => {lc($idtype) => $idvalue}}
2944 if ($result && $result->{count}) {
2945 if ($result->{count} > 1) {
2946 $item = NCIP::Problem->new(
2948 ProblemType => 'Non-Unique Item',
2949 ProblemDetail => 'More than one item matches the request.',
2950 ProblemElement => '',
2951 ProblemValue => $idvalue
2955 my $bibid = $result->{ids}->[0]->[0];
2956 $item = $U->simplereq(
2958 'open-ils.pcrud.retrieve.bre',
2959 $self->{session}->{authtoken},
2967 # Search for holds using the user and copy_details information:
2971 my $copy_details = shift;
2975 # Retrieve all of the user's active holds, and then search them in Perl.
2976 my $holds_list = $U->simplereq(
2978 'open-ils.circ.holds.retrieve',
2979 $self->{session}->{authtoken},
2984 if ($holds_list && @$holds_list) {
2986 # Look for title holds (the most common), first:
2987 my $targetid = $copy_details->{mvr}->doc_id();
2988 @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2990 # Look for volume holds, the next most common:
2991 $targetid = $copy_details->{volume}->id();
2992 @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2995 # Look for copy and force holds, the least likely.
2996 $targetid = $copy_details->{copy}->id();
2997 @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
2999 # There should only be 1, at this point, if there are any.
3008 # Standalone, "helper" functions. These do not take an object or
3011 # Check if a user is past their expiration date.
3016 # Users might not expire. If so, they have no expire_date.
3017 if ($user->expire_date()) {
3018 my $expires = DateTime::Format::ISO8601->parse_datetime(
3019 cleanse_ISO8601($user->expire_date())
3021 my $now = DateTime->now()->epoch();
3022 $expired = $now > $expires;
3028 # Creates a NCIP Problem from an event. Takes a string for the problem
3029 # type, the event hashref (or a string to use for the detail), and
3030 # optional arguments for the ProblemElement and ProblemValue fields.
3031 sub _problem_from_event {
3032 my ($type, $evt, $element, $value) = @_;
3038 my ($textcode, $desc);
3040 # Get the textcode, if available. Otherwise, use the ilsevent
3041 # "id," if available.
3042 if ($evt->{textcode}) {
3043 $textcode = $evt->{textcode};
3044 } elsif ($evt->{ilsevent}) {
3045 $textcode = $evt->{ilsevent};
3048 # Get the description. We favor translated descriptions over
3049 # the English in ils_events.xml.
3051 $desc = $evt->{desc};
3054 # Check if $type was set. As an "undocumented" feature, you
3055 # can pass undef, and we'll use the textcode from the event.
3062 # Set the detail from some combination of the above.
3065 } elsif ($textcode eq 'PERM_FAILURE') {
3066 if ($evt->{ilsperm}) {
3067 $detail = "Permission denied: " . $evt->{ilsperm};
3068 $detail =~ s/\.override$//;
3070 } elsif ($textcode) {
3071 $detail = "ILS returned $textcode error.";
3073 $detail = 'Detail not available.';
3080 return NCIP::Problem->new(
3082 ProblemType => ($type) ? $type : 'Temporary Processing Failure',
3083 ProblemDetail => ($detail) ? $detail : 'Detail not available.',
3084 ProblemElement => ($element) ? $element : 'NULL',
3085 ProblemValue => ($value) ? $value : 'NULL'
3090 # "Fix" dates for output so they validate against the schema
3093 my $out = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($date));
3094 $out->set_time_zone('UTC');
3095 return $out->iso8601();