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 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1016 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1017 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1020 UserId => NCIP::User::Id->new(
1022 UserIdentifierType => 'Barcode Id',
1023 UserIdentifierValue => $user->card->barcode()
1026 RequestType => $request->{$message}->{RequestType},
1027 RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1029 # Look for UserElements requested and add it to the response:
1030 my $elements = $request->{$message}->{UserElementType};
1032 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1033 my $optionalfields = $self->handle_user_elements($user, $elements);
1034 $data->{UserOptionalFields} = $optionalfields;
1036 $elements = $request->{$message}->{ItemElementType};
1038 $copy_details = $self->find_copy_details_by_item($item) unless ($copy_details);
1039 $elements = [$elements] unless (ref($elements) eq 'ARRAY');
1040 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1041 $data->{ItemOptionalFields} = $optionalfields;
1044 $response->data($data);
1050 =head2 cancelrequestitem
1052 $response = $ils->cancelrequestitem($request);
1054 Handle the NCIP CancelRequestItem message.
1058 sub cancelrequestitem {
1060 my $request = shift;
1061 # Check our session and login if necessary:
1062 $self->login() unless ($self->checkauth());
1065 my $message = $self->parse_request_type($request);
1066 my $response = NCIP::Response->new({type => $message . 'Response'});
1067 $response->header($self->make_header($request));
1069 # UserId is required by the standard, but we might not really need it.
1070 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1071 if (ref($user_barcode) eq 'NCIP::Problem') {
1072 $response->problem($user_barcode);
1075 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1076 if (ref($user) eq 'NCIP::Problem') {
1077 $response->problem($user);
1081 # See if we got a ItemId and a barcode:
1083 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1084 if (ref($item_barcode) ne 'NCIP::Problem') {
1085 # Retrieve the copy details.
1086 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1087 unless ($copy_details) {
1088 # Return an Unknown Item problem unless we find the copy.
1092 ProblemType => 'Unknown Item',
1093 ProblemDetail => "Item with barcode $item_barcode is not known.",
1094 ProblemElement => $item_idfield,
1095 ProblemValue => $item_barcode
1103 # See if we got a RequestId:
1105 if ($request->{$message}->{RequestId}) {
1106 $requestid = NCIP::RequestId->new(
1108 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1109 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1110 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1115 # Just a note: In the below, we cannot rely on the hold or transit
1116 # fields of the copy_details, even if we have retrieved it. This
1117 # is because that hold and transit may not be the ones that we're
1118 # looking for, i.e. they could be for another patron, etc.
1120 # See if we can find the hold:
1123 $hold = $U->simplereq(
1125 'open-ils.pcrud.retrieve.ahr',
1126 $self->{session}->{authtoken},
1127 $requestid->{RequestIdentifierValue},
1128 {flesh => 1, flesh_fields => {ahr => ['transit']}}
1131 # Report a problem that we couldn't find a hold by that id.
1135 ProblemType => 'Unknown Request',
1136 ProblemDetail => 'No request with this identifier found',
1137 ProblemElement => 'RequestIdentifierValue',
1138 ProblemValue => $requestid->{RequestIdentifierValue}
1142 } elsif ($hold->cancel_time()) {
1146 ProblemType => 'Request Already Canceled',
1147 ProblemDetail => 'Request has already been canceled',
1148 ProblemElement => 'RequestIdentifierValue',
1149 ProblemValue => $requestid->{RequestIdentifierValue}
1153 } elsif ($hold->transit()) {
1157 ProblemType => 'Request Already Processed',
1158 ProblemDetail => 'Request has already been processed',
1159 ProblemElement => 'RequestIdentifierValue',
1160 ProblemValue => $requestid->{RequestIdentifierValue}
1164 } elsif ($hold->usr() == $user->id()) {
1165 # Check the target matches the copy information, if any,
1166 # that we were given.
1168 if ($copy_details) {
1169 if ($hold->hold_type() eq 'V') {
1170 $obj_id = $copy_details->{volume}->id();
1171 } elsif ($hold->hold_type() eq 'T') {
1172 $obj_id = $copy_details->{mvr}->doc_id();
1173 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1174 $obj_id = $copy_details->{copy}->id();
1177 if ($obj_id && $hold->target() != $obj_id) {
1181 ProblemType => 'Request Not For This Item',
1182 ProblemDetail => "Request is not for this item",
1183 ProblemElement => $item_idfield,
1184 ProblemElement => $item_barcode
1189 $self->cancel_hold($hold);
1191 RequestId => $requestid,
1192 UserId => NCIP::User::Id->new(
1194 UserIdentifierType => 'Barcode Id',
1195 UserIdentifierValue => $user->card->barcode()
1199 # Look for UserElements requested and add it to the response:
1200 my $elements = $request->{$message}->{UserElementType};
1202 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1203 my $optionalfields = $self->handle_user_elements($user, $elements);
1204 $data->{UserOptionalFields} = $optionalfields;
1206 $elements = $request->{$message}->{ItemElementType};
1207 if ($elements && $copy_details) {
1208 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1209 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1210 $data->{ItemOptionalFields} = $optionalfields;
1212 $response->data($data);
1215 # Report a problem that the hold is not for this user.
1219 ProblemType => 'Request Not For This User',
1220 ProblemDetail => 'Request is not for this user.',
1221 ProblemElement => $user_idfield,
1222 ProblemValue => $user_barcode
1228 # At this point, we *must have* an ItemId and therefore
1229 # $copy_details, so return the problem from looking up the
1230 # barcode if we don't have $copy_details.
1231 if (!$copy_details) {
1232 $response->problem($item_barcode);
1234 # We have to search for the hold based on the copy details and
1235 # the user. We'll need to search for copy (or force) holds, a
1236 # volume hold, or a title hold.
1237 $hold = $self->_hold_search($user, $copy_details);
1238 if ($hold && $hold->transit()) {
1242 ProblemType => 'Request Already Processed',
1243 ProblemDetail => 'Request has already been processed',
1244 ProblemElement => 'RequestIdentifierValue',
1245 ProblemValue => $requestid->{RequestIdentifierValue}
1250 $self->cancel_hold($hold);
1252 RequestId => NCIP::RequestId->new(
1254 RequestIdentifierType => 'SYSNUMBER',
1255 RequestIdentifierValue => $hold->id()
1258 UserId => NCIP::User::Id->new(
1260 UserIdentifierType => 'Barcode Id',
1261 UserIdentifierValue => $user->card->barcode()
1265 # Look for UserElements requested and add it to the response:
1266 my $elements = $request->{$message}->{UserElementType};
1268 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1269 my $optionalfields = $self->handle_user_elements($user, $elements);
1270 $data->{UserOptionalFields} = $optionalfields;
1272 $elements = $request->{$message}->{ItemElementType};
1273 if ($elements && $copy_details) {
1274 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1275 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1276 $data->{ItemOptionalFields} = $optionalfields;
1278 $response->data($data);
1283 ProblemType => 'Unknown Request',
1284 ProblemDetail => 'No request found for the item and user',
1285 ProblemElement => 'NULL',
1286 ProblemValue => 'NULL'
1297 =head1 METHODS USEFUL to SUBCLASSES
1299 =head2 handle_user_elements
1300 $useroptionalfield = $ils->handle_user_elements($user, $elements);
1302 Returns NCIP::User::OptionalFields for the given user and arrayref of
1307 sub handle_user_elements {
1310 my $elements = shift;
1311 my $optionalfields = NCIP::User::OptionalFields->new();
1313 # First, we'll look for name information.
1314 if (grep {$_ eq 'Name Information'} @$elements) {
1315 my $name = NCIP::StructuredPersonalUserName->new();
1316 $name->Surname($user->family_name());
1317 $name->GivenName($user->first_given_name());
1318 $name->Prefix($user->prefix());
1319 $name->Suffix($user->suffix());
1320 $optionalfields->NameInformation($name);
1323 # Next, check for user address information.
1324 if (grep {$_ eq 'User Address Information'} @$elements) {
1327 # See if the user has any valid, physcial addresses.
1328 foreach my $addr (@{$user->addresses()}) {
1329 next if ($U->is_true($addr->pending()));
1330 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
1331 my $structured = NCIP::StructuredAddress->new();
1332 $structured->Line1($addr->street1());
1333 $structured->Line2($addr->street2());
1334 $structured->Locality($addr->city());
1335 $structured->Region($addr->state());
1336 $structured->PostalCode($addr->post_code());
1337 $structured->Country($addr->country());
1338 $address->PhysicalAddress(
1339 NCIP::PhysicalAddress->new(
1341 StructuredAddress => $structured,
1342 Type => 'Postal Address'
1346 push @$addresses, $address;
1349 # Right now, we're only sharing email address if the user
1351 if ($user->email()) {
1352 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
1353 $address->ElectronicAddress(
1354 NCIP::ElectronicAddress->new({
1356 Data=>$user->email()
1359 push @$addresses, $address;
1361 # Auto-graphics asked for the phone numbers.
1362 if ($user->day_phone()) {
1363 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Day Phone'});
1364 $address->ElectronicAddress(
1365 NCIP::ElectronicAddress->new(
1368 Data=>$user->day_phone()
1372 push @$addresses, $address;
1374 if ($user->evening_phone()) {
1375 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Evening Phone'});
1376 $address->ElectronicAddress(
1377 NCIP::ElectronicAddress->new(
1379 Type=>'Evening Phone',
1380 Data=>$user->evening_phone()
1384 push @$addresses, $address;
1386 if ($user->other_phone()) {
1387 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Other Phone'});
1388 $address->ElectronicAddress(
1389 NCIP::ElectronicAddress->new(
1391 Type=>'Other Phone',
1392 Data=>$user->other_phone()
1396 push @$addresses, $address;
1399 $optionalfields->UserAddressInformation($addresses);
1402 # Check for User Privilege.
1403 if (grep {$_ eq 'User Privilege'} @$elements) {
1404 # Get the user's group:
1405 my $pgt = $U->simplereq(
1407 'open-ils.pcrud.retrieve.pgt',
1408 $self->{session}->{authtoken},
1412 my $privilege = NCIP::User::Privilege->new();
1413 $privilege->AgencyId($user->home_ou->shortname());
1414 $privilege->AgencyUserPrivilegeType($pgt->name());
1415 $privilege->ValidToDate(_fix_date($user->expire_date()));
1416 $privilege->ValidFromDate(_fix_date($user->create_date()));
1418 my $status = 'Active';
1419 if (_expired($user)) {
1420 $status = 'Expired';
1421 } elsif ($U->is_true($user->barred())) {
1423 } elsif (!$U->is_true($user->active())) {
1424 $status = 'Inactive';
1427 $privilege->UserPrivilegeStatus(
1428 NCIP::User::PrivilegeStatus->new({
1429 UserPrivilegeStatusType => $status
1434 $optionalfields->UserPrivilege([$privilege]);
1438 # Check for Block Or Trap.
1439 if (grep {$_ eq 'Block Or Trap'} @$elements) {
1442 # First, let's check if the profile is blocked from ILL.
1443 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1444 my $block = NCIP::User::BlockOrTrap->new();
1445 $block->AgencyId($user->home_ou->shortname());
1446 $block->BlockOrTrapType('Block Interlibrary Loan');
1447 push @$blocks, $block;
1450 # Next, we loop through the user's standing penalties
1451 # looking for blocks on CIRC, HOLD, and RENEW.
1452 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
1453 foreach my $penalty (@{$user->standing_penalties()}) {
1454 next unless($penalty->standing_penalty->block_list());
1455 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
1456 my $ou = $U->simplereq(
1458 'open-ils.pcrud.retrieve.aou',
1459 $self->{session}->{authtoken},
1460 $penalty->org_unit()
1464 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
1465 my $bot = NCIP::User::BlockOrTrap->new();
1466 $bot->AgencyId($ou->shortname());
1467 $bot->BlockOrTrapType('Block Checkout');
1468 push @$blocks, $bot;
1473 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
1474 my $bot = NCIP::User::BlockOrTrap->new();
1475 $bot->AgencyId($ou->shortname());
1476 $bot->BlockOrTrapType('Block Holds');
1477 push @$blocks, $bot;
1482 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
1483 my $bot = NCIP::User::BlockOrTrap->new();
1484 $bot->AgencyId($ou->shortname());
1485 $bot->BlockOrTrapType('Block Renewals');
1486 push @$blocks, $bot;
1490 # Stop after we report one of each, even if more
1492 last if ($have_circ && $have_renew && $have_hold);
1495 $optionalfields->BlockOrTrap($blocks);
1498 return $optionalfields;
1501 =head2 handle_item_elements
1505 sub handle_item_elements {
1508 my $elements = shift;
1509 my $optionalfields = NCIP::Item::OptionalFields->new();
1511 my $details; # In case we need for more than one.
1513 if (grep {$_ eq 'Bibliographic Description'} @$elements) {
1515 # Check for a precat copy, 'cause it is simple.
1516 if ($copy->dummy_title()) {
1517 $description = NCIP::Item::BibliographicDescription->new();
1518 $description->Title($copy->dummy_title());
1519 $description->Author($copy->dummy_author());
1520 if ($copy->dummy_isbn()) {
1521 $description->BibliographicItemId(
1522 NCIP::Item::BibliographicItemId->new(
1524 BibliographicItemIdentifier => $copy->dummy_isbn(),
1525 BibliographicItemIdentifierCode => 'ISBN'
1531 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1532 $description = NCIP::Item::BibliographicDescription->new();
1533 $description->Title($details->{mvr}->title());
1534 $description->Author($details->{mvr}->author());
1535 $description->BibliographicRecordId(
1536 NCIP::Item::BibliographicRecordId->new(
1538 BibliographicRecordIdentifier => $details->{mvr}->doc_id(),
1539 BibliographicRecordIdentifierCode => 'SYSNUMBER'
1543 if ($details->{mvr}->publisher()) {
1544 $description->Publisher($details->{mvr}->publisher());
1546 if ($details->{mvr}->pubdate()) {
1547 $description->PublicationDate($details->{mvr}->pubdate());
1549 if ($details->{mvr}->edition()) {
1550 $description->Edition($details->{mvr}->edition());
1553 $optionalfields->BibliographicDescription($description) if ($description);
1556 if (grep {$_ eq 'Item Description'} @$elements) {
1557 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1558 # Call Number is the only field we currently return. We also
1559 # do not attempt to retun a prefix and suffix. Someone else
1560 # can deal with that if they want it.
1561 if ($details->{volume}) {
1562 $optionalfields->ItemDescription(
1563 NCIP::Item::Description->new(
1564 {CallNumber => $details->{volume}->label()}
1570 if (grep {$_ eq 'Circulation Status'} @$elements) {
1571 my $status = $copy->status();
1572 $status = $self->retrieve_copy_status($status) unless (ref($status));
1573 $optionalfields->CirculationStatus($status->name()) if ($status);
1576 if (grep {$_ eq 'Date Due'} @$elements) {
1577 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1578 if ($details->{circ}) {
1579 if (!$details->{circ}->checkin_time()) {
1580 $optionalfields->DateDue(_fix_date($details->{circ}->due_date()));
1585 if (grep {$_ eq 'Item Use Restriction Type'} @$elements) {
1586 $optionalfields->ItemUseRestrictionType('None');
1589 if (grep {$_ eq 'Physical Condition'} @$elements) {
1590 $optionalfields->PhysicalCondition(
1591 NCIP::Item::PhysicalCondition->new(
1592 {PhysicalConditionType => 'Unknown'}
1597 return $optionalfields;
1604 Login to Evergreen via OpenSRF. It uses internal state from the
1605 configuration file to login.
1609 # Login via OpenSRF to Evergreen.
1613 # Get the authentication seed.
1614 my $seed = $U->simplereq(
1616 'open-ils.auth.authenticate.init',
1617 $self->{config}->{credentials}->{username}
1622 my $response = $U->simplereq(
1624 'open-ils.auth.authenticate.complete',
1626 username => $self->{config}->{credentials}->{username},
1627 password => md5_hex(
1628 $seed . md5_hex($self->{config}->{credentials}->{password})
1631 workstation => $self->{config}->{credentials}->{workstation}
1635 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1636 $self->{session}->{authtime} = $response->{payload}->{authtime};
1638 # Set/reset the work_ou and user data in case something changed.
1640 # Retrieve the work_ou as an object.
1641 $self->{session}->{work_ou} = $U->simplereq(
1643 'open-ils.pcrud.search.aou',
1644 $self->{session}->{authtoken},
1645 {shortname => $self->{config}->{credentials}->{work_ou}}
1648 # We need the user information in order to do some things.
1649 $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1657 $valid = $ils->checkauth();
1659 Returns 1 if the object a 'valid' authtoken, 0 if not.
1666 # We use AppUtils to do the heavy lifting.
1667 if (defined($self->{session})) {
1668 if ($U->check_user_session($self->{session}->{authtoken})) {
1675 # If we reach here, we don't have a session, so we are definitely
1680 =head2 retrieve_user_by_barcode
1682 $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1684 Do a fleshed retrieve of a patron by barcode. Return the patron if
1685 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1687 The id field argument is used for the ProblemElement field in the
1688 NCIP::Problem object.
1690 An invalid patron is one where the barcode is not found in the
1691 database, the patron is deleted, or the barcode used to retrieve the
1692 patron is not active. The problem element is also returned if an error
1693 occurs during the retrieval.
1697 sub retrieve_user_by_barcode {
1698 my ($self, $barcode, $idfield) = @_;
1699 my $result = $U->simplereq(
1701 'open-ils.actor.user.fleshed.retrieve_by_barcode',
1702 $self->{session}->{authtoken},
1707 # Check for a failure, or a deleted, inactive, or expired user,
1708 # and if so, return empty userdata.
1709 if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1710 || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1712 my $problem = NCIP::Problem->new();
1713 $problem->ProblemType('Unknown User');
1714 $problem->ProblemDetail("User with barcode $barcode unknown");
1715 $problem->ProblemElement($idfield);
1716 $problem->ProblemValue($barcode);
1723 =head2 retrieve_user_by_id
1725 $user = $ils->retrieve_user_by_id($id);
1727 Similar to C<retrieve_user_by_barcode> but takes the user's database
1728 id rather than barcode. This is useful when you have a circulation or
1729 hold and need to get information about the user's involved in the hold
1732 It returns a fleshed user on success or undef on failure.
1736 sub retrieve_user_by_id {
1737 my ($self, $id) = @_;
1739 # Do a fleshed retrieve of the patron, and flesh the fields that
1740 # we would normally use.
1741 my $result = $U->simplereq(
1743 'open-ils.actor.user.fleshed.retrieve',
1744 $self->{session}->{authtoken},
1746 [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1748 # Check for an error.
1749 undef($result) if ($result && $U->event_code($result));
1754 =head2 check_user_for_problems
1756 $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1758 This function checks if a user has a blocked profile or any from a
1759 list of provided blocks. If it does, then a NCIP::Problem object is
1760 returned, otherwise an undefined value is returned.
1762 The list of blocks appears as additional arguments after the user. You
1763 can provide any value(s) that might appear in a standing penalty block
1764 lit in Evergreen. The example above checks for HOLD, CIRC, and
1765 RENEW. Any number of such values can be provided. If none are
1766 provided, the function only checks if the patron's profiles appears in
1767 the object's blocked profiles list.
1769 It stops on the first matching block, if any.
1773 sub check_user_for_problems {
1778 # Fill this in if we have a problem, otherwise just return it.
1781 # First, check the user's profile.
1782 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1783 $problem = NCIP::Problem->new(
1785 ProblemType => 'User Blocked',
1786 ProblemDetail => 'User blocked from inter-library loan',
1787 ProblemElement => 'NULL',
1788 ProblemValue => 'NULL'
1793 # Next, check if the patron has one of the indicated blocks.
1795 foreach my $penalty (@{$user->standing_penalties()}) {
1796 if ($penalty->standing_penalty->block_list()) {
1797 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1798 foreach my $block (@blocks) {
1799 if (grep {$_ =~ /$block/} @pblocks) {
1800 $problem = NCIP::Problem->new(
1802 ProblemType => 'User Blocked',
1803 ProblemDetail => 'User blocked from ' .
1804 ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1805 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1806 ProblemElement => 'NULL',
1807 ProblemValue => 'NULL'
1821 =head2 check_circ_details
1823 $problem = $ils->check_circ_details($circ, $copy, $user);
1825 Checks if we can checkin or renew a circulation. That is, the
1826 circulation is still open (i.e. the copy is still checked out), if we
1827 either own the copy or are the circulation location, and if the
1828 circulation is for the optional $user argument. $circ and $copy are
1829 required. $user is optional.
1831 Returns a problem if any of the above conditions fail. Returns undef
1832 if they pass and we can proceed with the checkin or renewal.
1834 If the failure occurred on the copy-related checks, then the
1835 ProblemElement field will be undefined and needs to be filled in with
1836 the item id field name. If the check for the copy being checked out to
1837 the provided user fails, then both ProblemElement and ProblemValue
1838 fields will be empty and need to be filled in by the caller.
1842 sub check_circ_details {
1843 my ($self, $circ, $copy, $user) = @_;
1845 # Shortcut for the next check.
1846 my $ou_id = $self->{session}->{work_ou}->id();
1848 if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1849 # Item isn't checked out.
1850 return NCIP::Problem->new(
1852 ProblemType => 'Item Not Checked Out',
1853 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1854 ProblemValue => $copy->barcode()
1858 # Get data on the patron who has it checked out.
1859 my $circ_user = $self->retrieve_user_by_id($circ->usr());
1860 if ($user && $circ_user && $user->id() != $circ_user->id()) {
1861 # The ProblemElement and ProblemValue field need to be
1862 # filled in by the caller.
1863 return NCIP::Problem->new(
1865 ProblemType => 'Item Not Checked Out To This User',
1866 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1871 # If we get here, we're good to go.
1875 =head2 retrieve_copy_details_by_barcode
1877 $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1879 Look up and retrieve some copy details by the copy barcode. This
1880 method returns either a hashref with the copy details or undefined if
1881 no copy exists with that barcode or if some error occurs.
1883 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1885 This method differs from C<retrieve_user_by_barcode> in that a copy
1886 cannot be invalid if it exists and it is not always an error if no
1887 copy exists. In some cases, when handling AcceptItem, we might prefer
1888 there to be no copy.
1892 sub retrieve_copy_details_by_barcode {
1894 my $barcode = shift;
1896 my $copy = $U->simplereq(
1898 'open-ils.circ.copy_details.retrieve.barcode',
1899 $self->{session}->{authtoken},
1903 # If $copy is an event, return undefined.
1904 if ($copy && $U->event_code($copy)) {
1911 =head2 find_copy_details_by_item
1913 $copy_details = $ils->find_copy_details_by_item($item);
1915 This routine returns a copy_details hashref (See:
1916 retrieve_copy_details_by_barcode) for a given item. It attempts to
1917 find the "first" copy for the given item. If item is a call number it
1918 looks for the first, not deleted copy. If item is a bib, it looks for
1919 the first not deleted copy on the first not deleted call number. If
1920 item is a copy, it simply returns the details for the copy.
1924 sub find_copy_details_by_item {
1930 if (ref($item) eq 'Fieldmapper::biblio::record_entry') {
1931 my $acns = $U->simplereq(
1933 'open-ils.pcrud.search.acn.atomic',
1934 $self->{session}->{authtoken},
1936 record => $item->id(),
1940 ($item) = sort {$a->id() <=> $b->id()} @{$acns};
1943 if (ref($item) eq 'Fieldmapper::asset::call_number') {
1944 my $copies = $U->simplereq(
1946 'open-ils.pcrud.search.acp.atomic',
1947 $self->{session}->{authtoken},
1949 call_number => $item->id(),
1953 ($item) = sort {$a->id() <=> $b->id()} @{$copies};
1956 if (ref($item) eq 'Fieldmapper::asset::copy') {
1957 $details = $self->retrieve_copy_details_by_barcode($item->barcode());
1963 =head2 retrieve_copy_status
1965 $status = $ils->retrieve_copy_status($id);
1967 Retrive a copy status object by database ID.
1971 sub retrieve_copy_status {
1975 my $status = $U->simplereq(
1977 'open-ils.pcrud.retrieve.ccs',
1978 $self->{session}->{authtoken},
1985 =head2 retrieve_org_unit_by_shortname
1987 $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1989 Retrieves an org. unit from the database by shortname, and fleshes the
1990 ou_type field. Returns the org. unit as a Fieldmapper object or
1995 sub retrieve_org_unit_by_shortname {
1997 my $shortname = shift;
1999 my $aou = $U->simplereq(
2001 'open-ils.actor.org_unit.retrieve_by_shortname',
2005 # We want to retrieve the type and manually "flesh" the object.
2007 my $type = $U->simplereq(
2009 'open-ils.pcrud.retrieve.aout',
2010 $self->{session}->{authtoken},
2013 $aou->ou_type($type) if ($type);
2019 =head2 retrieve_copy_location
2021 $location = $ils->retrieve_copy_location($location_id);
2023 Retrieve a copy location based on id.
2027 sub retrieve_copy_location {
2031 my $location = $U->simplereq(
2033 'open-ils.pcrud.retrieve.acpl',
2034 $self->{session}->{authtoken},
2041 =head2 retrieve_biblio_record_entry
2043 $bre = $ils->retrieve_biblio_record_entry($bre_id);
2045 Given a biblio.record_entry.id, this method retrieves a bre object.
2049 sub retrieve_biblio_record_entry {
2053 my $bre = $U->simplereq(
2055 'open-ils.pcrud.retrieve.bre',
2056 $self->{session}->{authtoken},
2063 =head2 create_precat_copy
2066 barcode => '312340123456789',
2067 author => 'Public, John Q.',
2068 title => 'Magnum Opus',
2069 call_number => '005.82',
2070 publisher => 'Brick House',
2071 publication_date => '2014'
2074 $item = $ils->create_precat_copy($item_info);
2077 Create a "precat" copy to use for the incoming item using a hashref of
2078 item information. At a minimum, the barcode, author and title fields
2079 need to be filled in. The other fields are ignored if provided.
2081 This method is called by the AcceptItem handler if the C<use_precats>
2082 configuration option is turned on.
2086 sub create_precat_copy {
2088 my $item_info = shift;
2090 my $item = Fieldmapper::asset::copy->new();
2091 $item->barcode($item_info->{barcode});
2092 $item->call_number(OILS_PRECAT_CALL_NUMBER);
2093 $item->dummy_title($item_info->{title});
2094 $item->dummy_author($item_info->{author});
2095 $item->circ_lib($self->{session}->{work_ou}->id());
2096 $item->circulate('t');
2097 $item->holdable('t');
2098 $item->opac_visible('f');
2099 $item->deleted('f');
2100 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2101 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2104 $item->editor($self->{session}->{user}->id());
2105 $item->creator($self->{session}->{user}->id());
2108 # Actually create it:
2110 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2113 $xact = $ses->request(
2114 'open-ils.pcrud.transaction.begin',
2115 $self->{session}->{authtoken}
2117 $item = $ses->request(
2118 'open-ils.pcrud.create.acp',
2119 $self->{session}->{authtoken},
2122 $xact = $ses->request(
2123 'open-ils.pcrud.transaction.commit',
2124 $self->{session}->{authtoken}
2132 'open-ils.pcrud.transaction.rollback',
2133 $self->{session}->{authtoken}
2143 =head2 create_fuller_copy
2146 barcode => '31234003456789',
2147 author => 'Public, John Q.',
2148 title => 'Magnum Opus',
2149 call_number => '005.82',
2150 publisher => 'Brick House',
2151 publication_date => '2014'
2154 $item = $ils->create_fuller_copy($item_info);
2156 Creates a skeletal bibliographic record, call number, and copy for the
2157 incoming item using a hashref with item information in it. At a
2158 minimum, the barcode, author, title, and call_number fields must be
2161 This method is used by the AcceptItem handler if the C<use_precats>
2162 configuration option is NOT set.
2166 sub create_fuller_copy {
2168 my $item_info = shift;
2172 # We do everything in one transaction, because it should be atomic.
2173 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2177 $xact = $ses->request(
2178 'open-ils.pcrud.transaction.begin',
2179 $self->{session}->{authtoken}
2186 # The rest depends on there being a transaction.
2189 # Create the MARC record.
2190 my $record = MARC::Record->new();
2191 $record->encoding('UTF-8');
2192 $record->leader('00881nam a2200193 4500');
2193 my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
2195 push(@fields, MARC::Field->new('005', $datespec));
2196 push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
2197 push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
2198 # Publisher is a little trickier:
2199 if ($item_info->{publisher}) {
2200 my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
2201 $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
2202 push(@fields, $pub);
2204 # We have no idea if the author is personal corporate or something else, so we use a 720.
2205 push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
2206 $record->append_fields(@fields);
2207 my $marc = clean_marc($record);
2209 # Create the bib object.
2210 my $bib = Fieldmapper::biblio::record_entry->new();
2211 $bib->creator($self->{session}->{user}->id());
2212 $bib->editor($self->{session}->{user}->id());
2213 $bib->source($self->{bib_source}->id());
2220 $bib = $ses->request(
2221 'open-ils.pcrud.create.bre',
2222 $self->{session}->{authtoken},
2230 'open-ils.pcrud.transaction.rollback',
2231 $self->{session}->{authtoken}
2236 # Create the call number
2239 $acn = Fieldmapper::asset::call_number->new();
2240 $acn->creator($self->{session}->{user}->id());
2241 $acn->editor($self->{session}->{user}->id());
2242 $acn->label($item_info->{call_number});
2243 $acn->record($bib->id());
2244 $acn->owning_lib($self->{session}->{work_ou}->id());
2249 $acn = $ses->request(
2250 'open-ils.pcrud.create.acn',
2251 $self->{session}->{authtoken},
2259 'open-ils.pcrud.transaction.rollback',
2260 $self->{session}->{authtoken}
2268 $item = Fieldmapper::asset::copy->new();
2269 $item->barcode($item_info->{barcode});
2270 $item->call_number($acn->id());
2271 $item->circ_lib($self->{session}->{work_ou}->id);
2272 $item->circulate('t');
2273 if ($self->{config}->{items}->{use_force_holds}) {
2274 $item->holdable('f');
2276 $item->holdable('t');
2278 $item->opac_visible('f');
2279 $item->deleted('f');
2280 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2281 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2284 $item->editor($self->{session}->{user}->id);
2285 $item->creator($self->{session}->{user}->id);
2289 $item = $ses->request(
2290 'open-ils.pcrud.create.acp',
2291 $self->{session}->{authtoken},
2295 # Cross our fingers and commit the work.
2296 $xact = $ses->request(
2297 'open-ils.pcrud.transaction.commit',
2298 $self->{session}->{authtoken}
2305 'open-ils.pcrud.transaction.rollback',
2306 $self->{session}->{authtoken}
2307 )->gather(1) if ($xact);
2313 # We need to disconnect our session.
2316 # Now, we handle our asset stat_cat entries.
2318 # It would be nice to do these in the above transaction, but
2319 # pcrud does not support the ascecm object, yet.
2320 foreach my $entry (@{$self->{stat_cat_entries}}) {
2321 my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2323 $map->stat_cat($entry->stat_cat());
2324 $map->stat_cat_entry($entry->id());
2325 $map->owning_copy($item->id());
2326 # We don't really worry if it succeeds or not.
2329 'open-ils.circ.stat_cat.asset.copy_map.create',
2330 $self->{session}->{authtoken},
2341 $hold = $ils->place_hold($item, $user, $location, $expiration, $org_unit);
2343 This function places a hold on $item for $user for pickup at
2344 $location. If location is not provided or undefined, the user's home
2345 library is used as a fallback.
2347 The $expiration argument is optional and must be a properly formatted
2348 ISO date time. It will be used as the hold expire time, if
2349 provided. Otherwise the system default time will be used.
2351 The $org_unit parameter is only consulted in the event of $item being
2352 a biblio::record_entry object. In which case, it is expected to be
2353 undefined or an actor::org_unit object. If it is present, then its id
2354 and ou_type depth (if the ou_type field is fleshed) will be used to
2355 control the selection ou and selection depth for the hold. This
2356 essentially limits the hold to being filled by copies belonging to the
2357 specified org_unit or its children.
2359 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2360 (biblio::record_entry). The appropriate hold type will be placed
2361 depending on the object.
2363 On success, the method returns the object representing the hold. On
2364 failure, a NCIP::Problem object, describing the failure, is returned.
2372 my $location = shift;
2373 my $expiration = shift;
2374 my $org_unit = shift;
2376 # If $location is undefined, use the user's home_ou, which should
2377 # have been fleshed when the user was retrieved.
2378 $location = $user->home_ou() unless ($location);
2380 # $hold is the hold. $params is for the is_possible check.
2381 my ($hold, $params);
2383 # Prep the hold with fields common to all hold types:
2384 $hold = Fieldmapper::action::hold_request->new();
2385 $hold->isnew(1); # Just to make sure.
2386 $hold->target($item->id());
2387 $hold->usr($user->id());
2388 $hold->pickup_lib($location->id());
2389 $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2390 if (!$user->email()) {
2391 $hold->email_notify('f');
2392 $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2394 $hold->email_notify('t');
2398 $params = { pickup_lib => $location->id(), patronid => $user->id() };
2400 if (ref($item) eq 'Fieldmapper::asset::copy') {
2401 my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2402 $hold->hold_type($type);
2403 $hold->current_copy($item->id());
2404 $params->{hold_type} = $type;
2405 $params->{copy_id} = $item->id();
2406 } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2407 $hold->hold_type('V');
2408 $params->{hold_type} = 'V';
2409 $params->{volume_id} = $item->id();
2410 } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2411 $hold->hold_type('T');
2412 $params->{hold_type} = 'T';
2413 $params->{titleid} = $item->id();
2414 if ($org_unit && ref($org_unit) eq 'Fieldmapper::actor::org_unit') {
2415 $hold->selection_ou($org_unit->id());
2416 $hold->selection_depth($org_unit->ou_type->depth()) if (ref($org_unit->ou_type()));
2420 # Check for a duplicate hold:
2421 my $duplicate = $U->simplereq(
2423 'open-ils.pcrud.search.ahr',
2424 $self->{session}->{authtoken},
2426 hold_type => $hold->hold_type(),
2427 target => $hold->target(),
2428 usr => $hold->usr(),
2429 expire_time => {'>' => 'now'},
2430 cancel_time => undef,
2431 fulfillment_time => undef
2435 return NCIP::Problem->new(
2437 ProblemType => 'Duplicate Request',
2438 ProblemDetail => 'A request for this item already exists for this patron.',
2439 ProblemElement => 'NULL',
2440 ProblemValue => 'NULL'
2445 # Check if the hold is possible:
2446 my $r = $U->simplereq(
2448 'open-ils.circ.title_hold.is_possible',
2449 $self->{session}->{authtoken},
2453 if ($r->{success}) {
2454 $hold = $U->simplereq(
2456 'open-ils.circ.holds.create.override',
2457 $self->{session}->{authtoken},
2461 $hold = $hold->[0] if (ref($hold) eq 'ARRAY');
2462 $hold = _problem_from_event('Request Not Possible', $hold);
2464 # open-ils.circ.holds.create.override returns the id on
2465 # success, so we retrieve the full hold object from the
2466 # database to return it.
2467 $hold = $U->simplereq(
2469 'open-ils.pcrud.retrieve.ahr',
2470 $self->{session}->{authtoken},
2474 } elsif ($r->{last_event}) {
2475 $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2476 } elsif ($r->{textcode}) {
2477 $hold = _problem_from_event('Request Not Possible', $r);
2479 $hold = _problem_from_event('Request Not Possible');
2487 $ils->cancel_hold($hold);
2489 This method cancels the hold argument. It makes no checks on the hold,
2490 so if there are certain conditions that need to be fulfilled before
2491 the hold is canceled, then you must check them before calling this
2494 It returns undef on success or failure. If it fails, you've usually
2495 got bigger problems.
2503 my $r = $U->simplereq(
2505 'open-ils.circ.hold.cancel',
2506 $self->{session}->{authtoken},
2509 'Canceled via NCIPServer'
2517 $ils->delete_copy($copy);
2519 Deletes the copy, and if it is owned by our work_ou and not a precat,
2520 we also delete the volume and bib on which the copy depends.
2528 # Shortcut for ownership checks below.
2529 my $ou_id = $self->{session}->{work_ou}->id();
2531 # First, make sure the copy is not already deleted and we own it.
2532 return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2534 # Indicate we want to delete the copy.
2535 $copy->isdeleted(1);
2537 # Delete the copy using a backend call that will delete the copy,
2538 # the call number, and bib when appropriate.
2539 my $result = $U->simplereq(
2541 'open-ils.cat.asset.copy.fleshed.batch.update.override',
2542 $self->{session}->{authtoken},
2546 # We are currently not checking for succes or failure of the
2547 # above. At some point, someone may want to.
2552 =head2 copy_can_circulate
2554 $can_circulate = $ils->copy_can_circulate($copy);
2556 Check if the copy's location and the copy itself allow
2557 circulation. Return true if they do, and false if they do not.
2561 sub copy_can_circulate {
2565 my $location = $copy->location();
2566 unless (ref($location)) {
2567 $location = $self->retrieve_copy_location($location);
2570 return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2573 =head2 copy_can_fulfill
2575 $can_fulfill = $ils->copy_can_fulfill($copy);
2577 Check if the copy's location and the copy itself allow
2578 holds. Return true if they do, and false if they do not.
2582 sub copy_can_fulfill {
2586 my $location = $copy->location();
2587 unless (ref($location)) {
2588 $location = $self->retrieve_copy_location($location);
2591 return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2594 =head1 OVERRIDDEN PARENT METHODS
2596 =head2 find_user_barcode
2598 We dangerously override our parent's C<find_user_barcode> to return
2599 either the $barcode or a Problem object. In list context the barcode
2600 or problem will be the first argument and the id field, if any, will
2601 be the second. We also add a second, optional, argument to indicate a
2602 default value for the id field in the event of a failure to find
2603 anything at all. (Perl lets us get away with this.)
2607 sub find_user_barcode {
2609 my $request = shift;
2610 my $default = shift;
2613 my $message = $self->parse_request_type($request);
2614 if ($message eq 'LookupUser') {
2615 $default = 'AuthenticationInputData';
2617 $default = 'UserIdentifierValue';
2621 my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2624 $idfield = $default unless ($idfield);
2625 $value = NCIP::Problem->new();
2626 $value->ProblemType('Needed Data Missing');
2627 $value->ProblemDetail('Cannot find user barcode in message.');
2628 $value->ProblemElement($idfield);
2629 $value->ProblemValue('NULL');
2632 return (wantarray) ? ($value, $idfield) : $value;
2635 =head2 find_item_barcode
2637 We do pretty much the same thing as with C<find_user_barcode> for
2638 C<find_item_barcode>.
2642 sub find_item_barcode {
2644 my $request = shift;
2645 my $default = shift || 'ItemIdentifierValue';
2647 my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2650 $idfield = $default unless ($idfield);
2651 $value = NCIP::Problem->new();
2652 $value->ProblemType('Needed Data Missing');
2653 $value->ProblemDetail('Cannot find item barcode in message.');
2654 $value->ProblemElement($idfield);
2655 $value->ProblemValue('NULL');
2658 return (wantarray) ? ($value, $idfield) : $value;
2661 =head2 find_target_via_bibliographic_id
2663 $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2665 Searches for a bibliographic record to put on hold and returns an
2666 appropriate hold target item depending upon what it finds. If an
2667 appropriate, single target cannot be found, it returns an
2668 NCIP::Problem with the problem message.
2670 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2671 identifiers. If nothing is found, this method can return undef. (Gotta
2672 love Perl and untyped/weakly typed languages in general!)
2674 TODO: Figure out how to search OCLC numbers. We probably need to use
2675 "MARC Expert Search" if we don't want to do a JSON query on
2680 sub find_target_via_bibliographic_id {
2682 my @biblio_ids = @_;
2684 # The item that we find:
2687 # Id for our bib in Evergreen:
2690 # First, let's look for a SYSNUMBER:
2692 { ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'SYSNUMBER')
2693 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER')
2698 # BibliographicRecordId can have an AgencyId field if the
2699 # BibliographicRecordIdentifierCode is absent.
2700 if ($idobj->{AgencyId}) {
2701 $bibid = $idobj->{BibliographicRecordIdentifier};
2702 my $locname = $idobj->{AgencyId};
2704 $locname =~ s/^.*://;
2705 $loc = $self->retrieve_org_unit_by_shortname($locname);
2707 } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2708 $bibid = $idobj->{BibliographicRecordIdentifier};
2710 $bibid = $idobj->{BibliographicItemIdentifier};
2712 if ($bibid && $loc) {
2713 $item = $self->_call_number_search($bibid, $loc);
2715 $item = $U->simplereq(
2717 'open-ils.pcrud.retrieve.bre',
2718 $self->{session}->{authtoken},
2722 # Check if item is deleted so we'll look for more
2724 undef($item) if ($item && $U->is_true($item->deleted()));
2727 # Build an array of id objects based on the other identifier fields.
2730 ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISBN')
2731 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISBN')
2732 || ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISSN')
2733 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISSN')
2737 my $stashed_problem;
2738 # Reuse $idobj from above.
2739 foreach $idobj (@idobjs) {
2740 my ($idvalue, $idtype, $idfield);
2741 if ($_->{BibliographicItemIdentifier}) {
2742 $idvalue = $_->{BibliographicItemIdentifier};
2743 $idtype = $_->{BibliographicItemIdentifierCode};
2744 $idfield = 'BibliographicItemIdentifier';
2746 $idvalue = $_->{BibliographicRecordIdentifier};
2747 $idtype = $_->{BibliographicRecordIdentifierCode};
2748 $idfield = 'BibliographicRecordIdentifier';
2750 $item = $self->_bib_search($idvalue, $idtype);
2751 if (ref($item) eq 'NCIP::Problem') {
2752 $stashed_problem = $item unless($stashed_problem);
2753 $stashed_problem->ProblemElement($idfield);
2758 $item = $stashed_problem if (!$item && $stashed_problem);
2764 =head2 find_location_failover
2766 $location = $ils->find_location_failover($location, $request, $message);
2768 Attempts to retrieve an org_unit by shortname from the passed in
2769 $location. If that fails, $request and $message are used to lookup
2770 the ToAgencyId/AgencyId field and that is used. Returns an org_unit
2771 as retrieved by retrieve_org_unit_by_shortname if successful and undef
2776 sub find_location_failover {
2777 my ($self, $location, $request, $message) = @_;
2778 if ($request && !$message) {
2779 $message = $self->parse_request_type($request);
2783 # Because Auto-Graphics. (This should be configured somehow.)
2784 $location =~ s/^[^-]+-//;
2785 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2787 if ($request && $message && !$org_unit) {
2788 $location = $request->{$message}->{InitiationHeader}->{ToAgencyId}->{AgencyId};
2790 # Because Auto-Graphics. (This should be configured somehow.)
2791 $location =~ s/^[^-]+-//;
2792 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2799 # private subroutines not meant to be used directly by subclasses.
2800 # Most have to do with setup and/or state checking of implementation
2803 # Find, load, and parse our configuration file:
2807 # Find the configuration file via variables:
2808 my $file = OILS_NCIP_CONFIG_DEFAULT;
2809 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2811 $self->{config} = XMLin($file, NormaliseSpace => 2,
2812 ForceArray => ['block_profile', 'stat_cat_entry']);
2815 # Bootstrap OpenSRF::System and load the IDL.
2819 my $bootstrap_config = $self->{config}->{bootstrap};
2820 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2822 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2823 Fieldmapper->import(IDL => $idl);
2826 # Login and then initialize some object data based on the
2831 # Login to Evergreen.
2834 # Load the barred groups as pgt objects into a blocked_profiles
2836 $self->{blocked_profiles} = [];
2837 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2840 $pgt = $U->simplereq(
2842 'open-ils.pcrud.retrieve.pgt',
2843 $self->{session}->{authtoken},
2847 $pgt = $U->simplereq(
2849 'open-ils.pcrud.search.pgt',
2850 $self->{session}->{authtoken},
2854 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2857 # Load the bib source if we're not using precats.
2858 unless ($self->{config}->{items}->{use_precats}) {
2859 # Retrieve the default
2860 $self->{bib_source} = $U->simplereq(
2862 'open-ils.pcrud.retrieve.cbs',
2863 $self->{session}->{authtoken},
2864 BIB_SOURCE_DEFAULT);
2865 my $data = $self->{config}->{items}->{bib_source};
2867 $data = $data->[0] if (ref($data) eq 'ARRAY');
2870 $result = $U->simplereq(
2872 'open-ils.pcrud.retrieve.cbs',
2873 $self->{session}->{authtoken},
2877 $result = $U->simplereq(
2879 'open-ils.pcrud.search.cbs',
2880 $self->{session}->{authtoken},
2884 $self->{bib_source} = $result if ($result);
2888 # Load the required asset.stat_cat_entries:
2889 $self->{stat_cat_entries} = [];
2890 # First, make a regex for our ou and ancestors:
2891 my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2892 my $re = qr/(?:$ancestors)/;
2893 # Get the uniq stat_cat ids from the configuration:
2894 my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2895 # Retrieve all of the fleshed stat_cats and entries for the above.
2896 my $stat_cats = $U->simplereq(
2898 'open-ils.circ.stat_cat.asset.retrieve.batch',
2899 $self->{session}->{authtoken},
2902 foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2903 # Must have the stat_cat attr and the name, so we must have a
2905 next unless(ref $entry);
2906 my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2907 push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2911 # Search asset.call_number by a bre.id and location object. Return the
2912 # "closest" call_number if found, undef otherwise.
2913 sub _call_number_search {
2916 my $location = shift;
2918 # At some point, this should be smarter, and we should retrieve
2919 # ancestors and descendants and search with a JSON query or some
2920 # such with results ordered by proximity to the original location,
2921 # but I don't have time to implement that right now.
2922 my $acn = $U->simplereq(
2924 'open-ils.pcrud.search.acn',
2925 $self->{session}->{authtoken},
2926 {record => $bibid, owning_lib => $location->id()}
2932 # Do a multiclass.query to search for items by isbn or issn.
2935 my $idvalue = shift;
2939 my $result = $U->simplereq(
2941 'open-ils.search.biblio.multiclass',
2942 {searches => {lc($idtype) => $idvalue}}
2945 if ($result && $result->{count}) {
2946 if ($result->{count} > 1) {
2947 $item = NCIP::Problem->new(
2949 ProblemType => 'Non-Unique Item',
2950 ProblemDetail => 'More than one item matches the request.',
2951 ProblemElement => '',
2952 ProblemValue => $idvalue
2956 my $bibid = $result->{ids}->[0]->[0];
2957 $item = $U->simplereq(
2959 'open-ils.pcrud.retrieve.bre',
2960 $self->{session}->{authtoken},
2968 # Search for holds using the user and copy_details information:
2972 my $copy_details = shift;
2976 # Retrieve all of the user's active holds, and then search them in Perl.
2977 my $holds_list = $U->simplereq(
2979 'open-ils.circ.holds.retrieve',
2980 $self->{session}->{authtoken},
2985 if ($holds_list && @$holds_list) {
2987 # Look for title holds (the most common), first:
2988 my $targetid = $copy_details->{mvr}->doc_id();
2989 @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2991 # Look for volume holds, the next most common:
2992 $targetid = $copy_details->{volume}->id();
2993 @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2996 # Look for copy and force holds, the least likely.
2997 $targetid = $copy_details->{copy}->id();
2998 @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
3000 # There should only be 1, at this point, if there are any.
3009 # Standalone, "helper" functions. These do not take an object or
3012 # Check if a user is past their expiration date.
3017 # Users might not expire. If so, they have no expire_date.
3018 if ($user->expire_date()) {
3019 my $expires = DateTime::Format::ISO8601->parse_datetime(
3020 cleanse_ISO8601($user->expire_date())
3022 my $now = DateTime->now()->epoch();
3023 $expired = $now > $expires;
3029 # Creates a NCIP Problem from an event. Takes a string for the problem
3030 # type, the event hashref (or a string to use for the detail), and
3031 # optional arguments for the ProblemElement and ProblemValue fields.
3032 sub _problem_from_event {
3033 my ($type, $evt, $element, $value) = @_;
3039 my ($textcode, $desc);
3041 # Get the textcode, if available. Otherwise, use the ilsevent
3042 # "id," if available.
3043 if ($evt->{textcode}) {
3044 $textcode = $evt->{textcode};
3045 } elsif ($evt->{ilsevent}) {
3046 $textcode = $evt->{ilsevent};
3049 # Get the description. We favor translated descriptions over
3050 # the English in ils_events.xml.
3052 $desc = $evt->{desc};
3055 # Check if $type was set. As an "undocumented" feature, you
3056 # can pass undef, and we'll use the textcode from the event.
3063 # Set the detail from some combination of the above.
3066 } elsif ($textcode eq 'PERM_FAILURE') {
3067 if ($evt->{ilsperm}) {
3068 $detail = "Permission denied: " . $evt->{ilsperm};
3069 $detail =~ s/\.override$//;
3071 } elsif ($textcode) {
3072 $detail = "ILS returned $textcode error.";
3074 $detail = 'Detail not available.';
3081 return NCIP::Problem->new(
3083 ProblemType => ($type) ? $type : 'Temporary Processing Failure',
3084 ProblemDetail => ($detail) ? $detail : 'Detail not available.',
3085 ProblemElement => ($element) ? $element : 'NULL',
3086 ProblemValue => ($value) ? $value : 'NULL'
3091 # "Fix" dates for output so they validate against the schema
3094 my $out = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($date));
3095 $out->set_time_zone('UTC');
3096 return $out->iso8601();