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 # Use the user's main card as the UserId.
167 my $id = NCIP::User::Id->new({
168 UserIdentifierType => 'Barcode',
169 UserIdnetifierValue => $user->card->barcode()
171 $userdata->UserId($id);
173 # Check if they requested any optional fields and return those.
174 my $elements = $request->{$message_type}->{UserElementType};
176 $elements = [$elements] unless (ref $elements eq 'ARRAY');
177 my $optionalfields = $self->handle_user_elements($user, $elements);
178 $userdata->UserOptionalFields($optionalfields);
181 $response->data($userdata);
188 $ils->acceptitem($request);
190 Processes an AcceptItem request.
198 # Check our session and login if necessary.
199 $self->login() unless ($self->checkauth());
201 # Common preparation.
202 my $message = $self->parse_request_type($request);
203 my $response = NCIP::Response->new({type => $message . 'Response'});
204 $response->header($self->make_header($request));
206 # We only accept holds for the time being.
207 if ($request->{$message}->{RequestedActionType} =~ /^hold\W/i) {
208 # We need the item id or we can't do anything at all.
209 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
210 if (ref($item_barcode) eq 'NCIP::Problem') {
211 $response->problem($item_barcode);
215 # We need to find a patron barcode or we can't look anyone up
217 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request, 'UserIdentifierValue');
218 if (ref($user_barcode) eq 'NCIP::Problem') {
219 $response->problem($user_barcode);
222 # Look up our patron by barcode:
223 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
224 if (ref($user) eq 'NCIP::Problem') {
225 $response->problem($user);
228 # We're doing patron checks before looking for bibliographic
229 # information and creating the item because problems with the
230 # patron are more likely to occur.
231 my $problem = $self->check_user_for_problems($user, 'HOLD');
233 $response->problem($problem);
237 # Check if the item barcode already exists:
238 my $item = $self->retrieve_copy_details_by_barcode($item_barcode);
240 # What to do here was not defined in the
241 # specification. Since the copies that we create this way
242 # should get deleted when checked in, it would be an error
243 # if we try to create another one. It means that something
244 # has gone wrong somewhere.
248 ProblemType => 'Duplicate Item',
249 ProblemDetail => "Item with barcode $item_barcode already exists.",
250 ProblemElement => $item_idfield,
251 ProblemValue => $item_barcode
258 # Now, we have to create our new copy and/or bib and call number.
260 # First, we have to gather the necessary information from the
261 # request. Store in a hashref for convenience. We may write a
262 # method to get this information in the future if we find we
263 # need it in other handlers. Such a function would be a
264 # candidate to go into our parent, NCIP::ILS.
266 barcode => $item_barcode,
267 call_number => $request->{$message}->{ItemOptionalFields}->{ItemDescription}->{CallNumber},
268 title => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Title},
269 author => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Author},
270 publisher => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Publisher},
271 publication_date => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{PublicationDate},
272 medium => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{MediumType},
273 electronic => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{ElectronicResource}
276 if ($self->{config}->{items}->{use_precats}) {
277 # We only need to create a precat copy.
278 $item = $self->create_precat_copy($item_info);
280 # We have to create a "partial" bib record, a call number and a copy.
281 $item = $self->create_fuller_copy($item_info);
284 # If we failed to create the copy, report a problem.
288 ProblemType => 'Temporary Processing Failure',
289 ProblemDetail => 'Failed to create the item in the system',
290 ProblemElement => $item_idfield,
291 ProblemValue => $item_barcode
297 # We try to find the pickup location in our database. It's OK
298 # if it does not exist, the user's home library will be used
300 my $location = $self->find_location_failover($request->{$message}->{PickupLocation}, $request, $message);
302 # Now, we place the hold on the newly created copy on behalf
303 # of the patron retrieved above.
304 my $hold = $self->place_hold($item, $user, $location);
305 if (ref($hold) eq 'NCIP::Problem') {
306 $response->problem($hold);
310 # We return the RequestId and optionally, the ItemID. We'll
311 # just return what was sent to us, since we ignored all of it
314 $data->{RequestId} = NCIP::RequestId->new(
316 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
317 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
318 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
321 $data->{ItemId} = NCIP::Item::Id->new(
323 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
324 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
325 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
328 $response->data($data);
331 my $problem = NCIP::Problem->new();
332 $problem->ProblemType('Unauthorized Combination Of Element Values For System');
333 $problem->ProblemDetail('We only support Hold For Pickup');
334 $problem->ProblemElement('RequestedActionType');
335 $problem->ProblemValue($request->{$message}->{RequestedActionType});
336 $response->problem($problem);
344 $response = $ils->checkinitem($request);
346 Checks the item in if we can find the barcode in the message. It
347 returns problems if it cannot find the item in the system or if the
348 item is not checked out.
350 It could definitely use some more brains at some point as it does not
351 fully support everything that the standard allows. It also does not
352 really check if the checkin succeeded or not.
360 # Check our session and login if necessary:
361 $self->login() unless ($self->checkauth());
364 my $message = $self->parse_request_type($request);
365 my $response = NCIP::Response->new({type => $message . 'Response'});
366 $response->header($self->make_header($request));
368 # We need the copy barcode from the message.
369 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
370 if (ref($item_barcode) eq 'NCIP::Problem') {
371 $response->problem($item_barcode);
375 # Retrieve the copy details.
376 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
378 # Return an Unknown Item problem unless we find the copy.
382 ProblemType => 'Unknown Item',
383 ProblemDetail => "Item with barcode $item_barcode is not known.",
384 ProblemElement => $item_idfield,
385 ProblemValue => $item_barcode
392 # Check if a UserId was provided. If so, this is the patron to
393 # whom the copy should be checked out.
395 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
396 # We ignore the problem, because the UserId is optional.
397 if (ref($user_barcode) ne 'NCIP::Problem') {
398 $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
399 # We don't ignore a problem here, however.
400 if (ref($user) eq 'NCIP::Problem') {
401 $response->problem($user);
407 my $copy = $details->{copy};
409 # Look for a circulation and examine its information:
410 my $circ = $details->{circ};
412 # Check the circ details to see if the copy is checked out and, if
413 # the patron was provided, that it is checked out to the patron in
414 # question. We also verify the copy ownership and circulation
416 my $problem = $self->check_circ_details($circ, $copy, $user);
418 # We need to fill in some information, however.
419 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
420 $problem->ProblemValue($user_barcode);
421 $problem->ProblemElement($user_idfield);
422 } elsif (!$problem->ProblemElement()) {
423 $problem->ProblemElement($item_idfield);
425 $response->problem($problem);
429 # Checkin parameters. We want to skip hold targeting or making
430 # transits, to force the checkin despite the copy status, as
431 # well as void overdues.
433 copy_barcode => $copy->barcode(),
438 my $result = $U->simplereq(
440 'open-ils.circ.checkin.override',
441 $self->{session}->{authtoken},
444 if (ref($result) eq 'ARRAY') {
445 $result = $result->[0];
447 if ($result->{textcode} eq 'SUCCESS') {
448 # Delete the copy. Since delete_copy checks ownership
449 # before attempting to delete the copy, we don't bother
450 # checking who owns it.
451 $self->delete_copy($copy);
452 # We need the circulation user for the information below, so we retrieve it.
453 my $circ_user = $self->retrieve_user_by_id($circ->usr());
455 ItemId => NCIP::Item::Id->new(
457 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
458 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
459 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
462 UserId => NCIP::User::Id->new(
464 UserIdentifierType => 'Barcode Id',
465 UserIdentifierValue => $circ_user->card->barcode()
470 # Look for UserElements requested and add it to the response:
471 my $elements = $request->{$message}->{UserElementType};
473 $elements = [$elements] unless (ref $elements eq 'ARRAY');
474 my $optionalfields = $self->handle_user_elements($circ_user, $elements);
475 $data->{UserOptionalFields} = $optionalfields;
477 $elements = $request->{$message}->{ItemElementType};
479 $elements = [$elements] unless (ref $elements eq 'ARRAY');
480 my $optionalfields = $self->handle_item_elements($copy, $elements);
481 $data->{ItemOptionalFields} = $optionalfields;
484 $response->data($data);
486 # At some point in the future, we should probably check if
487 # they requested optional user or item elements and return
488 # those. For the time being, we ignore those at the risk of
489 # being considered non-compliant.
491 $response->problem(_problem_from_event('Checkin Failed', $result));
499 $response = $ils->renewitem($request);
501 Handle the RenewItem message.
509 # Check our session and login if necessary:
510 $self->login() unless ($self->checkauth());
513 my $message = $self->parse_request_type($request);
514 my $response = NCIP::Response->new({type => $message . 'Response'});
515 $response->header($self->make_header($request));
517 # We need the copy barcode from the message.
518 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
519 if (ref($item_barcode) eq 'NCIP::Problem') {
520 $response->problem($item_barcode);
524 # Retrieve the copy details.
525 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
527 # Return an Unknown Item problem unless we find the copy.
531 ProblemType => 'Unknown Item',
532 ProblemDetail => "Item with barcode $item_barcode is not known.",
533 ProblemElement => $item_idfield,
534 ProblemValue => $item_barcode
541 # User is required for RenewItem.
542 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
543 if (ref($user_barcode) eq 'NCIP::Problem') {
544 $response->problem($user_barcode);
547 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
548 if (ref($user) eq 'NCIP::Problem') {
549 $response->problem($user);
554 my $copy = $details->{copy};
556 # Look for a circulation and examine its information:
557 my $circ = $details->{circ};
559 # Check the circ details to see if the copy is checked out and, if
560 # the patron was provided, that it is checked out to the patron in
561 # question. We also verify the copy ownership and circulation
563 my $problem = $self->check_circ_details($circ, $copy, $user);
565 # We need to fill in some information, however.
566 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
567 $problem->ProblemValue($user_barcode);
568 $problem->ProblemElement($user_idfield);
569 } elsif (!$problem->ProblemElement()) {
570 $problem->ProblemElement($item_idfield);
572 $response->problem($problem);
576 # Check if user is blocked from renewals:
577 $problem = $self->check_user_for_problems($user, 'RENEW');
579 # Replace the ProblemElement and ProblemValue fields.
580 $problem->ProblemElement($user_idfield);
581 $problem->ProblemValue($user_barcode);
582 $response->problem($problem);
586 # Check if the duration rule allows renewals. It should have been
587 # fleshed during the copy details retrieve.
588 my $rule = $circ->duration_rule();
589 unless (ref($rule)) {
590 $rule = $U->simplereq(
592 'open-ils.pcrud.retrieve.crcd',
593 $self->{session}->{authtoken},
597 if ($rule->max_renewals() < 1) {
601 ProblemType => 'Item Not Renewable',
602 ProblemDetail => 'Item may not be renewed.',
603 ProblemElement => $item_idfield,
604 ProblemValue => $item_barcode
611 # Check if there are renewals remaining on the latest circ:
612 if ($circ->renewal_remaining() < 1) {
616 ProblemType => 'Maximum Renewals Exceeded',
617 ProblemDetail => 'Renewal cannot proceed because the User has already renewed the Item the maximum number of times permitted.',
618 ProblemElement => $item_idfield,
619 ProblemValue => $item_barcode
626 # Now, we attempt the renewal. If it fails, we simply say that the
627 # user is not allowed to renew this item, without getting into
630 copy_id => $copy->id(),
631 patron_id => $user->id(),
634 my $r = $U->simplereq(
636 'open-ils.circ.renew.override',
637 $self->{session}->{authtoken},
641 # We only look at the first one, since more than one usually means
643 if (ref($r) eq 'ARRAY') {
646 if ($r->{textcode} ne 'SUCCESS') {
647 $problem = _problem_from_event('Renewal Failed', $r);
648 $response->problem($problem);
651 ItemId => NCIP::Item::Id->new(
653 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
654 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
655 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
658 UserId => NCIP::User::Id->new(
660 UserIdentifierType => 'Barcode Id',
661 UserIdentifierValue => $user->card->barcode()
665 # We need to retrieve the copy details again to refresh our
666 # circ information to get the new due date.
667 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
668 $circ = $details->{circ};
669 $data->{DateDue} = _fix_date($circ->due_date());
671 # Look for UserElements requested and add it to the response:
672 my $elements = $request->{$message}->{UserElementType};
674 $elements = [$elements] unless (ref $elements eq 'ARRAY');
675 my $optionalfields = $self->handle_user_elements($user, $elements);
676 $data->{UserOptionalFields} = $optionalfields;
678 $elements = $request->{$message}->{ItemElementType};
680 $elements = [$elements] unless (ref $elements eq 'ARRAY');
681 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
682 $data->{ItemOptionalFields} = $optionalfields;
685 $response->data($data);
688 # At some point in the future, we should probably check if
689 # they requested optional user or item elements and return
690 # those. For the time being, we ignore those at the risk of
691 # being considered non-compliant.
698 $response = $ils->checkoutitem($request);
700 Handle the Checkoutitem message.
708 # Check our session and login if necessary:
709 $self->login() unless ($self->checkauth());
712 my $message = $self->parse_request_type($request);
713 my $response = NCIP::Response->new({type => $message . 'Response'});
714 $response->header($self->make_header($request));
716 # We need the copy barcode from the message.
717 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
718 if (ref($item_barcode) eq 'NCIP::Problem') {
719 $response->problem($item_barcode);
723 # Retrieve the copy details.
724 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
726 # Return an Unknown Item problem unless we find the copy.
730 ProblemType => 'Unknown Item',
731 ProblemDetail => "Item with barcode $item_barcode is not known.",
732 ProblemElement => $item_idfield,
733 ProblemValue => $item_barcode
740 # User is required for CheckOutItem.
741 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
742 if (ref($user_barcode) eq 'NCIP::Problem') {
743 $response->problem($user_barcode);
746 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
747 if (ref($user) eq 'NCIP::Problem') {
748 $response->problem($user);
753 my $copy = $details->{copy};
755 # Check if the copy can circulate.
756 unless ($self->copy_can_circulate($copy)) {
760 ProblemType => 'Item Does Not Circulate',
761 ProblemDetail => "Item with barcode $item_barcode does not circulate.",
762 ProblemElement => $item_idfield,
763 ProblemValue => $item_barcode
770 # Look for a circulation and examine its information:
771 my $circ = $details->{circ};
773 # Check if the item is already checked out.
774 if ($circ && !$circ->checkin_time()) {
778 ProblemType => 'Item Already Checked Out',
779 ProblemDetail => "Item with barcode $item_barcode is already checked out.",
780 ProblemElement => $item_idfield,
781 ProblemValue => $item_barcode
788 # Check if user is blocked from circulation:
789 my $problem = $self->check_user_for_problems($user, 'CIRC');
791 # Replace the ProblemElement and ProblemValue fields.
792 $problem->ProblemElement($user_idfield);
793 $problem->ProblemValue($user_barcode);
794 $response->problem($problem);
798 # Check for the copy being in transit and receive or abort it.
799 my $transit = $U->simplereq(
800 'open-ils.circ.open_copy_transit.retrieve',
801 $self->{session}->{authtoken},
804 if (ref($transit) eq 'Fieldmapper::action::transit_copy') {
805 if ($transit->dest() == $self->{session}->{work_ou}->id()) {
806 my $r = $U->simplereq(
808 'open-ils.circ.copy_transit.receive',
809 $self->{session}->{authtoken},
810 {copyid => $copy->id()}
812 } elsif ($transit->source() == $self->{session}->{work_ou}->id()) {
813 my $r = $U->simplereq(
815 'open-ils.circ.transit.abort',
816 $self->{session}->{authtoken},
817 {copyid => $copy->id()}
822 # Now, we attempt the check out. If it fails, we simply say that
823 # the user is not allowed to check out this item, without getting
826 copy_id => $copy->id(),
827 patron_id => $user->id(),
829 my $r = $U->simplereq(
831 'open-ils.circ.checkout.full.override',
832 $self->{session}->{authtoken},
836 # We only look at the first one, since more than one usually means
838 if (ref($r) eq 'ARRAY') {
841 if ($r->{textcode} ne 'SUCCESS') {
842 $problem = _problem_from_event('Check Out Failed', $r);
843 $response->problem($problem);
846 ItemId => NCIP::Item::Id->new(
848 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
849 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
850 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
853 UserId => NCIP::User::Id->new(
855 UserIdentifierType => 'Barcode Id',
856 UserIdentifierValue => $user->card->barcode()
860 # We need to retrieve the copy details again to refresh our
861 # circ information to get the due date.
862 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
863 $circ = $details->{circ};
864 $data->{DateDue} = _fix_date($circ->due_date());
866 # Look for UserElements requested and add it to the response:
867 my $elements = $request->{$message}->{UserElementType};
869 $elements = [$elements] unless (ref $elements eq 'ARRAY');
870 my $optionalfields = $self->handle_user_elements($user, $elements);
871 $data->{UserOptionalFields} = $optionalfields;
873 $elements = $request->{$message}->{ItemElementType};
875 $elements = [$elements] unless (ref $elements eq 'ARRAY');
876 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
877 $data->{ItemOptionalFields} = $optionalfields;
880 $response->data($data);
883 # At some point in the future, we should probably check if
884 # they requested optional user or item elements and return
885 # those. For the time being, we ignore those at the risk of
886 # being considered non-compliant.
893 $response = $ils->requestitem($request);
895 Handle the NCIP RequestItem message.
902 # Check our session and login if necessary:
903 $self->login() unless ($self->checkauth());
906 my $message = $self->parse_request_type($request);
907 my $response = NCIP::Response->new({type => $message . 'Response'});
908 $response->header($self->make_header($request));
910 # Because we need to have a user to place a hold, because the user
911 # is likely to have problems, and because getting the item
912 # information for the hold is trickier than getting the user
913 # information, we'll do the user first and short circuit out of
914 # the function if there is a problem with the user.
915 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
916 if (ref($user_barcode) eq 'NCIP::Problem') {
917 $response->problem($user_barcode);
920 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
921 if (ref($user) eq 'NCIP::Problem') {
922 $response->problem($user);
925 my $problem = $self->check_user_for_problems($user, 'HOLD');
927 $response->problem($problem);
931 # RequestItem is a blast. We need to check if we have a copy
932 # barcode and/or if we have BibliographicIds. If we have both or
933 # either, we then need to figure out what we're placing the hold
934 # on, a copy, a volume or a bib. We don't currently do part holds,
935 # but maybe we should some day. We can also be sent more than 1
936 # BibliographicId, so we look for certain identifiers first, and
937 # then others in decreasing preference: SYSNUMBER, ISBN, and ISSN.
939 # Not to mention that there are two kinds of BibliographicId field
940 # with different field names, and both can be intermixed in an
941 # incoming message! (I just /love/ this nonsense.)
943 # This here is the thing we're going to put on hold:
946 # We need copy details if we find in a couple of places below.
949 # We need the copy barcode from the message.
950 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
951 if (ref($item_barcode) ne 'NCIP::Problem') {
952 # Retrieve the copy details.
953 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
954 unless ($copy_details) {
955 # Return an Unknown Item problem unless we find the copy.
959 ProblemType => 'Unknown Item',
960 ProblemDetail => "Item with barcode $item_barcode is not known.",
961 ProblemElement => $item_idfield,
962 ProblemValue => $item_barcode
968 $item = $copy_details->{volume}; # We place a volume hold.
971 # We weren't given copy information to target, or we can't find
972 # it, so we need to look for a target via BibliographicId.
974 my @biblio_ids = $self->find_bibliographic_ids($request);
976 $item = $self->find_target_via_bibliographic_id(@biblio_ids);
980 # If we don't have an item, then blow up with a problem that may
981 # have been set when we went looking for the ItemId.
983 if (ref($item_barcode) eq 'NCIP::Problem') {
984 $response->problem($item_barcode);
989 ProblemType => 'Request Item Not Found',
990 ProblemDetail => 'Unable to determine the item to request from input message.',
991 ProblemElement => 'NULL',
992 ProblemValue => 'NULL'
998 } elsif (ref($item) eq 'NCIP::Problem') {
999 $response->problem($item);
1003 # We have an item. If we have a biblio.record_entry object,
1004 # Auto-Graphics expects us to place the hold such that it is
1005 # limited to the branch or system whose id they have given us.
1006 # We, therefore, look for an org_unit based on the ToAgencyId from
1007 # the InitiationHeader.
1009 if (ref($item) eq 'Fieldmapper::biblio::record_entry') {
1010 $ou = $self->find_location_failover(undef, $request, $message);
1013 # See if we were given a PickupLocation.
1015 if ($request->{$message}->{PickupLocation}) {
1016 my $loc = $request->{$message}->{PickupLocation};
1017 $loc =~ s/^.*://; # strip everything up to the last
1018 # semi-colon, if any.
1019 $location = $self->retrieve_org_unit_by_shortname($loc);
1022 # Look for a NeedBeforeDate to use as expiration...
1023 my $hold_expiration = $request->{$message}->{NeedBeforeDate};
1026 my $hold = $self->place_hold($item, $user, $location, $hold_expiration, $ou);
1027 if (ref($hold) eq 'NCIP::Problem') {
1028 $response->problem($hold);
1031 RequestId => NCIP::RequestId->new(
1033 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1034 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1035 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1038 UserId => NCIP::User::Id->new(
1040 UserIdentifierType => 'Barcode Id',
1041 UserIdentifierValue => $user->card->barcode()
1044 RequestType => $request->{$message}->{RequestType},
1045 RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1047 # Fill in the ItemId based on what we have.
1048 if ($item_barcode && ref($item_barcode) ne 'NCIP::Problem') {
1049 $data->{ItemId} = NCIP::Item::Id->new({
1050 ItemIdentifierValue => $item_barcode,
1051 ItemIdentifierType => 'Barcode'
1054 $data->{ItemId} = NCIP::Item::Id->new({
1055 ItemIdentifierValue => $item->id(),
1056 ItemIdentifierType => 'SYSNUMBER'
1060 # Look for UserElements requested and add it to the response:
1061 my $elements = $request->{$message}->{UserElementType};
1063 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1064 my $optionalfields = $self->handle_user_elements($user, $elements);
1065 $data->{UserOptionalFields} = $optionalfields;
1067 $elements = $request->{$message}->{ItemElementType};
1069 $copy_details = $self->find_copy_details_by_item($item) unless ($copy_details);
1070 $elements = [$elements] unless (ref($elements) eq 'ARRAY');
1071 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1072 $data->{ItemOptionalFields} = $optionalfields;
1075 $response->data($data);
1081 =head2 cancelrequestitem
1083 $response = $ils->cancelrequestitem($request);
1085 Handle the NCIP CancelRequestItem message.
1089 sub cancelrequestitem {
1091 my $request = shift;
1092 # Check our session and login if necessary:
1093 $self->login() unless ($self->checkauth());
1096 my $message = $self->parse_request_type($request);
1097 my $response = NCIP::Response->new({type => $message . 'Response'});
1098 $response->header($self->make_header($request));
1100 # UserId is required by the standard, but we might not really need it.
1101 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1102 if (ref($user_barcode) eq 'NCIP::Problem') {
1103 $response->problem($user_barcode);
1106 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1107 if (ref($user) eq 'NCIP::Problem') {
1108 $response->problem($user);
1112 # See if we got a ItemId and a barcode:
1114 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1115 if (ref($item_barcode) ne 'NCIP::Problem') {
1116 # Retrieve the copy details.
1117 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1118 unless ($copy_details) {
1119 # Return an Unknown Item problem unless we find the copy.
1123 ProblemType => 'Unknown Item',
1124 ProblemDetail => "Item with barcode $item_barcode is not known.",
1125 ProblemElement => $item_idfield,
1126 ProblemValue => $item_barcode
1134 # See if we got a RequestId:
1136 if ($request->{$message}->{RequestId}) {
1137 $requestid = NCIP::RequestId->new(
1139 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1140 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1141 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1146 # Just a note: In the below, we cannot rely on the hold or transit
1147 # fields of the copy_details, even if we have retrieved it. This
1148 # is because that hold and transit may not be the ones that we're
1149 # looking for, i.e. they could be for another patron, etc.
1151 # See if we can find the hold:
1154 $hold = $U->simplereq(
1156 'open-ils.pcrud.retrieve.ahr',
1157 $self->{session}->{authtoken},
1158 $requestid->{RequestIdentifierValue},
1159 {flesh => 1, flesh_fields => {ahr => ['transit']}}
1162 # Report a problem that we couldn't find a hold by that id.
1166 ProblemType => 'Unknown Request',
1167 ProblemDetail => 'No request with this identifier found',
1168 ProblemElement => 'RequestIdentifierValue',
1169 ProblemValue => $requestid->{RequestIdentifierValue}
1173 } elsif ($hold->cancel_time()) {
1177 ProblemType => 'Request Already Canceled',
1178 ProblemDetail => 'Request has already been canceled',
1179 ProblemElement => 'RequestIdentifierValue',
1180 ProblemValue => $requestid->{RequestIdentifierValue}
1184 } elsif ($hold->transit()) {
1188 ProblemType => 'Request Already Processed',
1189 ProblemDetail => 'Request has already been processed',
1190 ProblemElement => 'RequestIdentifierValue',
1191 ProblemValue => $requestid->{RequestIdentifierValue}
1195 } elsif ($hold->usr() == $user->id()) {
1196 # Check the target matches the copy information, if any,
1197 # that we were given.
1199 if ($copy_details) {
1200 if ($hold->hold_type() eq 'V') {
1201 $obj_id = $copy_details->{volume}->id();
1202 } elsif ($hold->hold_type() eq 'T') {
1203 $obj_id = $copy_details->{mvr}->doc_id();
1204 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1205 $obj_id = $copy_details->{copy}->id();
1208 if ($obj_id && $hold->target() != $obj_id) {
1212 ProblemType => 'Request Not For This Item',
1213 ProblemDetail => "Request is not for this item",
1214 ProblemElement => $item_idfield,
1215 ProblemElement => $item_barcode
1220 $self->cancel_hold($hold);
1222 RequestId => $requestid,
1223 UserId => NCIP::User::Id->new(
1225 UserIdentifierType => 'Barcode Id',
1226 UserIdentifierValue => $user->card->barcode()
1230 # Look for UserElements requested and add it to the response:
1231 my $elements = $request->{$message}->{UserElementType};
1233 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1234 my $optionalfields = $self->handle_user_elements($user, $elements);
1235 $data->{UserOptionalFields} = $optionalfields;
1237 $elements = $request->{$message}->{ItemElementType};
1238 if ($elements && $copy_details) {
1239 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1240 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1241 $data->{ItemOptionalFields} = $optionalfields;
1243 $response->data($data);
1246 # Report a problem that the hold is not for this user.
1250 ProblemType => 'Request Not For This User',
1251 ProblemDetail => 'Request is not for this user.',
1252 ProblemElement => $user_idfield,
1253 ProblemValue => $user_barcode
1259 # At this point, we *must have* an ItemId and therefore
1260 # $copy_details, so return the problem from looking up the
1261 # barcode if we don't have $copy_details.
1262 if (!$copy_details) {
1263 $response->problem($item_barcode);
1265 # We have to search for the hold based on the copy details and
1266 # the user. We'll need to search for copy (or force) holds, a
1267 # volume hold, or a title hold.
1268 $hold = $self->_hold_search($user, $copy_details);
1269 if ($hold && $hold->transit()) {
1273 ProblemType => 'Request Already Processed',
1274 ProblemDetail => 'Request has already been processed',
1275 ProblemElement => 'RequestIdentifierValue',
1276 ProblemValue => $requestid->{RequestIdentifierValue}
1281 $self->cancel_hold($hold);
1283 RequestId => NCIP::RequestId->new(
1285 RequestIdentifierType => 'SYSNUMBER',
1286 RequestIdentifierValue => $hold->id()
1289 UserId => NCIP::User::Id->new(
1291 UserIdentifierType => 'Barcode Id',
1292 UserIdentifierValue => $user->card->barcode()
1296 # Look for UserElements requested and add it to the response:
1297 my $elements = $request->{$message}->{UserElementType};
1299 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1300 my $optionalfields = $self->handle_user_elements($user, $elements);
1301 $data->{UserOptionalFields} = $optionalfields;
1303 $elements = $request->{$message}->{ItemElementType};
1304 if ($elements && $copy_details) {
1305 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1306 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1307 $data->{ItemOptionalFields} = $optionalfields;
1309 $response->data($data);
1314 ProblemType => 'Unknown Request',
1315 ProblemDetail => 'No request found for the item and user',
1316 ProblemElement => 'NULL',
1317 ProblemValue => 'NULL'
1328 =head1 METHODS USEFUL to SUBCLASSES
1330 =head2 handle_user_elements
1331 $useroptionalfield = $ils->handle_user_elements($user, $elements);
1333 Returns NCIP::User::OptionalFields for the given user and arrayref of
1338 sub handle_user_elements {
1341 my $elements = shift;
1342 my $optionalfields = NCIP::User::OptionalFields->new();
1344 # First, we'll look for name information.
1345 if (grep {$_ eq 'Name Information'} @$elements) {
1346 my $name = NCIP::StructuredPersonalUserName->new();
1347 $name->Surname($user->family_name());
1348 $name->GivenName($user->first_given_name());
1349 $name->Prefix($user->prefix());
1350 $name->Suffix($user->suffix());
1351 $optionalfields->NameInformation($name);
1354 # Next, check for user address information.
1355 if (grep {$_ eq 'User Address Information'} @$elements) {
1358 # See if the user has any valid, physcial addresses.
1359 foreach my $addr (@{$user->addresses()}) {
1360 next if ($U->is_true($addr->pending()));
1361 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
1362 my $structured = NCIP::StructuredAddress->new();
1363 $structured->Line1($addr->street1());
1364 $structured->Line2($addr->street2());
1365 $structured->Locality($addr->city());
1366 $structured->Region($addr->state());
1367 $structured->PostalCode($addr->post_code());
1368 $structured->Country($addr->country());
1369 $address->PhysicalAddress(
1370 NCIP::PhysicalAddress->new(
1372 StructuredAddress => $structured,
1373 Type => 'Postal Address'
1377 push @$addresses, $address;
1380 # Right now, we're only sharing email address if the user
1382 if ($user->email()) {
1383 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
1384 $address->ElectronicAddress(
1385 NCIP::ElectronicAddress->new({
1387 Data=>$user->email()
1390 push @$addresses, $address;
1392 # Auto-graphics asked for the phone numbers.
1393 if ($user->day_phone()) {
1394 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Day Phone'});
1395 $address->ElectronicAddress(
1396 NCIP::ElectronicAddress->new(
1399 Data=>$user->day_phone()
1403 push @$addresses, $address;
1405 if ($user->evening_phone()) {
1406 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Evening Phone'});
1407 $address->ElectronicAddress(
1408 NCIP::ElectronicAddress->new(
1410 Type=>'Evening Phone',
1411 Data=>$user->evening_phone()
1415 push @$addresses, $address;
1417 if ($user->other_phone()) {
1418 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Other Phone'});
1419 $address->ElectronicAddress(
1420 NCIP::ElectronicAddress->new(
1422 Type=>'Other Phone',
1423 Data=>$user->other_phone()
1427 push @$addresses, $address;
1430 $optionalfields->UserAddressInformation($addresses);
1433 # Check for User Privilege.
1434 if (grep {$_ eq 'User Privilege'} @$elements) {
1435 # Get the user's group:
1436 my $pgt = $U->simplereq(
1438 'open-ils.pcrud.retrieve.pgt',
1439 $self->{session}->{authtoken},
1443 my $privilege = NCIP::User::Privilege->new();
1444 $privilege->AgencyId($user->home_ou->shortname());
1445 $privilege->AgencyUserPrivilegeType($pgt->name());
1446 $privilege->ValidToDate(_fix_date($user->expire_date()));
1447 $privilege->ValidFromDate(_fix_date($user->create_date()));
1449 my $status = 'Active';
1450 if (_expired($user)) {
1451 $status = 'Expired';
1452 } elsif ($U->is_true($user->barred())) {
1454 } elsif (!$U->is_true($user->active())) {
1455 $status = 'Inactive';
1458 $privilege->UserPrivilegeStatus(
1459 NCIP::User::PrivilegeStatus->new({
1460 UserPrivilegeStatusType => $status
1465 $optionalfields->UserPrivilege([$privilege]);
1469 # Check for Block Or Trap.
1470 if (grep {$_ eq 'Block Or Trap'} @$elements) {
1473 # First, let's check if the profile is blocked from ILL.
1474 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1475 my $block = NCIP::User::BlockOrTrap->new();
1476 $block->AgencyId($user->home_ou->shortname());
1477 $block->BlockOrTrapType('Block Interlibrary Loan');
1478 push @$blocks, $block;
1481 # Next, we loop through the user's standing penalties
1482 # looking for blocks on CIRC, HOLD, and RENEW.
1483 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
1484 foreach my $penalty (@{$user->standing_penalties()}) {
1485 next unless($penalty->standing_penalty->block_list());
1486 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
1487 my $ou = $U->simplereq(
1489 'open-ils.pcrud.retrieve.aou',
1490 $self->{session}->{authtoken},
1491 $penalty->org_unit()
1495 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
1496 my $bot = NCIP::User::BlockOrTrap->new();
1497 $bot->AgencyId($ou->shortname());
1498 $bot->BlockOrTrapType('Block Checkout');
1499 push @$blocks, $bot;
1504 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
1505 my $bot = NCIP::User::BlockOrTrap->new();
1506 $bot->AgencyId($ou->shortname());
1507 $bot->BlockOrTrapType('Block Holds');
1508 push @$blocks, $bot;
1513 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
1514 my $bot = NCIP::User::BlockOrTrap->new();
1515 $bot->AgencyId($ou->shortname());
1516 $bot->BlockOrTrapType('Block Renewals');
1517 push @$blocks, $bot;
1521 # Stop after we report one of each, even if more
1523 last if ($have_circ && $have_renew && $have_hold);
1526 $optionalfields->BlockOrTrap($blocks);
1529 return $optionalfields;
1532 =head2 handle_item_elements
1536 sub handle_item_elements {
1539 my $elements = shift;
1540 my $optionalfields = NCIP::Item::OptionalFields->new();
1542 my $details; # In case we need for more than one.
1544 if (grep {$_ eq 'Bibliographic Description'} @$elements) {
1546 # Check for a precat copy, 'cause it is simple.
1547 if ($copy->dummy_title()) {
1548 $description = NCIP::Item::BibliographicDescription->new();
1549 $description->Title($copy->dummy_title());
1550 $description->Author($copy->dummy_author());
1551 if ($copy->dummy_isbn()) {
1552 $description->BibliographicItemId(
1553 NCIP::Item::BibliographicItemId->new(
1555 BibliographicItemIdentifier => $copy->dummy_isbn(),
1556 BibliographicItemIdentifierCode => 'ISBN'
1562 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1563 $description = NCIP::Item::BibliographicDescription->new();
1564 $description->Title($details->{mvr}->title());
1565 $description->Author($details->{mvr}->author());
1566 $description->BibliographicRecordId(
1567 NCIP::Item::BibliographicRecordId->new(
1569 BibliographicRecordIdentifier => $details->{mvr}->doc_id(),
1570 BibliographicRecordIdentifierCode => 'SYSNUMBER'
1574 if ($details->{mvr}->publisher()) {
1575 $description->Publisher($details->{mvr}->publisher());
1577 if ($details->{mvr}->pubdate()) {
1578 $description->PublicationDate($details->{mvr}->pubdate());
1580 if ($details->{mvr}->edition()) {
1581 $description->Edition($details->{mvr}->edition());
1584 $optionalfields->BibliographicDescription($description) if ($description);
1587 if (grep {$_ eq 'Item Description'} @$elements) {
1588 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1589 # Call Number is the only field we currently return. We also
1590 # do not attempt to retun a prefix and suffix. Someone else
1591 # can deal with that if they want it.
1592 if ($details->{volume}) {
1593 $optionalfields->ItemDescription(
1594 NCIP::Item::Description->new(
1595 {CallNumber => $details->{volume}->label()}
1601 if (grep {$_ eq 'Circulation Status'} @$elements) {
1602 my $status = $copy->status();
1603 $status = $self->retrieve_copy_status($status) unless (ref($status));
1604 $optionalfields->CirculationStatus($status->name()) if ($status);
1607 if (grep {$_ eq 'Date Due'} @$elements) {
1608 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1609 if ($details->{circ}) {
1610 if (!$details->{circ}->checkin_time()) {
1611 $optionalfields->DateDue(_fix_date($details->{circ}->due_date()));
1616 if (grep {$_ eq 'Item Use Restriction Type'} @$elements) {
1617 $optionalfields->ItemUseRestrictionType('None');
1620 if (grep {$_ eq 'Physical Condition'} @$elements) {
1621 $optionalfields->PhysicalCondition(
1622 NCIP::Item::PhysicalCondition->new(
1623 {PhysicalConditionType => 'Unknown'}
1628 return $optionalfields;
1635 Login to Evergreen via OpenSRF. It uses internal state from the
1636 configuration file to login.
1640 # Login via OpenSRF to Evergreen.
1644 # Get the authentication seed.
1645 my $seed = $U->simplereq(
1647 'open-ils.auth.authenticate.init',
1648 $self->{config}->{credentials}->{username}
1653 my $response = $U->simplereq(
1655 'open-ils.auth.authenticate.complete',
1657 username => $self->{config}->{credentials}->{username},
1658 password => md5_hex(
1659 $seed . md5_hex($self->{config}->{credentials}->{password})
1662 workstation => $self->{config}->{credentials}->{workstation}
1666 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1667 $self->{session}->{authtime} = $response->{payload}->{authtime};
1669 # Set/reset the work_ou and user data in case something changed.
1671 # Retrieve the work_ou as an object.
1672 $self->{session}->{work_ou} = $U->simplereq(
1674 'open-ils.pcrud.search.aou',
1675 $self->{session}->{authtoken},
1676 {shortname => $self->{config}->{credentials}->{work_ou}}
1679 # We need the user information in order to do some things.
1680 $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1688 $valid = $ils->checkauth();
1690 Returns 1 if the object a 'valid' authtoken, 0 if not.
1697 # We use AppUtils to do the heavy lifting.
1698 if (defined($self->{session})) {
1699 if ($U->check_user_session($self->{session}->{authtoken})) {
1706 # If we reach here, we don't have a session, so we are definitely
1711 =head2 retrieve_user_by_barcode
1713 $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1715 Do a fleshed retrieve of a patron by barcode. Return the patron if
1716 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1718 The id field argument is used for the ProblemElement field in the
1719 NCIP::Problem object.
1721 An invalid patron is one where the barcode is not found in the
1722 database, the patron is deleted, or the barcode used to retrieve the
1723 patron is not active. The problem element is also returned if an error
1724 occurs during the retrieval.
1728 sub retrieve_user_by_barcode {
1729 my ($self, $barcode, $idfield) = @_;
1730 my $result = $U->simplereq(
1732 'open-ils.actor.user.fleshed.retrieve_by_barcode',
1733 $self->{session}->{authtoken},
1738 # Check for a failure, or a deleted, inactive, or expired user,
1739 # and if so, return empty userdata.
1740 if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1741 || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1743 my $problem = NCIP::Problem->new();
1744 $problem->ProblemType('Unknown User');
1745 $problem->ProblemDetail("User with barcode $barcode unknown");
1746 $problem->ProblemElement($idfield);
1747 $problem->ProblemValue($barcode);
1754 =head2 retrieve_user_by_id
1756 $user = $ils->retrieve_user_by_id($id);
1758 Similar to C<retrieve_user_by_barcode> but takes the user's database
1759 id rather than barcode. This is useful when you have a circulation or
1760 hold and need to get information about the user's involved in the hold
1763 It returns a fleshed user on success or undef on failure.
1767 sub retrieve_user_by_id {
1768 my ($self, $id) = @_;
1770 # Do a fleshed retrieve of the patron, and flesh the fields that
1771 # we would normally use.
1772 my $result = $U->simplereq(
1774 'open-ils.actor.user.fleshed.retrieve',
1775 $self->{session}->{authtoken},
1777 [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1779 # Check for an error.
1780 undef($result) if ($result && $U->event_code($result));
1785 =head2 check_user_for_problems
1787 $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1789 This function checks if a user has a blocked profile or any from a
1790 list of provided blocks. If it does, then a NCIP::Problem object is
1791 returned, otherwise an undefined value is returned.
1793 The list of blocks appears as additional arguments after the user. You
1794 can provide any value(s) that might appear in a standing penalty block
1795 lit in Evergreen. The example above checks for HOLD, CIRC, and
1796 RENEW. Any number of such values can be provided. If none are
1797 provided, the function only checks if the patron's profiles appears in
1798 the object's blocked profiles list.
1800 It stops on the first matching block, if any.
1804 sub check_user_for_problems {
1809 # Fill this in if we have a problem, otherwise just return it.
1812 # First, check the user's profile.
1813 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1814 $problem = NCIP::Problem->new(
1816 ProblemType => 'User Blocked',
1817 ProblemDetail => 'User blocked from inter-library loan',
1818 ProblemElement => 'NULL',
1819 ProblemValue => 'NULL'
1824 # Next, check if the patron has one of the indicated blocks.
1826 foreach my $penalty (@{$user->standing_penalties()}) {
1827 if ($penalty->standing_penalty->block_list()) {
1828 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1829 foreach my $block (@blocks) {
1830 if (grep {$_ =~ /$block/} @pblocks) {
1831 $problem = NCIP::Problem->new(
1833 ProblemType => 'User Blocked',
1834 ProblemDetail => 'User blocked from ' .
1835 ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1836 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1837 ProblemElement => 'NULL',
1838 ProblemValue => 'NULL'
1852 =head2 check_circ_details
1854 $problem = $ils->check_circ_details($circ, $copy, $user);
1856 Checks if we can checkin or renew a circulation. That is, the
1857 circulation is still open (i.e. the copy is still checked out), if we
1858 either own the copy or are the circulation location, and if the
1859 circulation is for the optional $user argument. $circ and $copy are
1860 required. $user is optional.
1862 Returns a problem if any of the above conditions fail. Returns undef
1863 if they pass and we can proceed with the checkin or renewal.
1865 If the failure occurred on the copy-related checks, then the
1866 ProblemElement field will be undefined and needs to be filled in with
1867 the item id field name. If the check for the copy being checked out to
1868 the provided user fails, then both ProblemElement and ProblemValue
1869 fields will be empty and need to be filled in by the caller.
1873 sub check_circ_details {
1874 my ($self, $circ, $copy, $user) = @_;
1876 # Shortcut for the next check.
1877 my $ou_id = $self->{session}->{work_ou}->id();
1879 if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1880 # Item isn't checked out.
1881 return NCIP::Problem->new(
1883 ProblemType => 'Item Not Checked Out',
1884 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1885 ProblemValue => $copy->barcode()
1889 # Get data on the patron who has it checked out.
1890 my $circ_user = $self->retrieve_user_by_id($circ->usr());
1891 if ($user && $circ_user && $user->id() != $circ_user->id()) {
1892 # The ProblemElement and ProblemValue field need to be
1893 # filled in by the caller.
1894 return NCIP::Problem->new(
1896 ProblemType => 'Item Not Checked Out To This User',
1897 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1902 # If we get here, we're good to go.
1906 =head2 retrieve_copy_details_by_barcode
1908 $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1910 Look up and retrieve some copy details by the copy barcode. This
1911 method returns either a hashref with the copy details or undefined if
1912 no copy exists with that barcode or if some error occurs.
1914 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1916 This method differs from C<retrieve_user_by_barcode> in that a copy
1917 cannot be invalid if it exists and it is not always an error if no
1918 copy exists. In some cases, when handling AcceptItem, we might prefer
1919 there to be no copy.
1923 sub retrieve_copy_details_by_barcode {
1925 my $barcode = shift;
1927 my $copy = $U->simplereq(
1929 'open-ils.circ.copy_details.retrieve.barcode',
1930 $self->{session}->{authtoken},
1934 # If $copy is an event, return undefined.
1935 if ($copy && $U->event_code($copy)) {
1942 =head2 find_copy_details_by_item
1944 $copy_details = $ils->find_copy_details_by_item($item);
1946 This routine returns a copy_details hashref (See:
1947 retrieve_copy_details_by_barcode) for a given item. It attempts to
1948 find the "first" copy for the given item. If item is a call number it
1949 looks for the first, not deleted copy. If item is a bib, it looks for
1950 the first not deleted copy on the first not deleted call number. If
1951 item is a copy, it simply returns the details for the copy.
1955 sub find_copy_details_by_item {
1961 if (ref($item) eq 'Fieldmapper::biblio::record_entry') {
1962 my $acns = $U->simplereq(
1964 'open-ils.pcrud.search.acn.atomic',
1965 $self->{session}->{authtoken},
1967 record => $item->id(),
1971 ($item) = sort {$a->id() <=> $b->id()} @{$acns};
1974 if (ref($item) eq 'Fieldmapper::asset::call_number') {
1975 my $copies = $U->simplereq(
1977 'open-ils.pcrud.search.acp.atomic',
1978 $self->{session}->{authtoken},
1980 call_number => $item->id(),
1984 ($item) = sort {$a->id() <=> $b->id()} @{$copies};
1987 if (ref($item) eq 'Fieldmapper::asset::copy') {
1988 $details = $self->retrieve_copy_details_by_barcode($item->barcode());
1994 =head2 retrieve_copy_status
1996 $status = $ils->retrieve_copy_status($id);
1998 Retrive a copy status object by database ID.
2002 sub retrieve_copy_status {
2006 my $status = $U->simplereq(
2008 'open-ils.pcrud.retrieve.ccs',
2009 $self->{session}->{authtoken},
2016 =head2 retrieve_org_unit_by_shortname
2018 $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
2020 Retrieves an org. unit from the database by shortname, and fleshes the
2021 ou_type field. Returns the org. unit as a Fieldmapper object or
2026 sub retrieve_org_unit_by_shortname {
2028 my $shortname = shift;
2030 my $aou = $U->simplereq(
2032 'open-ils.actor.org_unit.retrieve_by_shortname',
2036 # We want to retrieve the type and manually "flesh" the object.
2038 my $type = $U->simplereq(
2040 'open-ils.pcrud.retrieve.aout',
2041 $self->{session}->{authtoken},
2044 $aou->ou_type($type) if ($type);
2050 =head2 retrieve_copy_location
2052 $location = $ils->retrieve_copy_location($location_id);
2054 Retrieve a copy location based on id.
2058 sub retrieve_copy_location {
2062 my $location = $U->simplereq(
2064 'open-ils.pcrud.retrieve.acpl',
2065 $self->{session}->{authtoken},
2072 =head2 retrieve_biblio_record_entry
2074 $bre = $ils->retrieve_biblio_record_entry($bre_id);
2076 Given a biblio.record_entry.id, this method retrieves a bre object.
2080 sub retrieve_biblio_record_entry {
2084 my $bre = $U->simplereq(
2086 'open-ils.pcrud.retrieve.bre',
2087 $self->{session}->{authtoken},
2094 =head2 create_precat_copy
2097 barcode => '312340123456789',
2098 author => 'Public, John Q.',
2099 title => 'Magnum Opus',
2100 call_number => '005.82',
2101 publisher => 'Brick House',
2102 publication_date => '2014'
2105 $item = $ils->create_precat_copy($item_info);
2108 Create a "precat" copy to use for the incoming item using a hashref of
2109 item information. At a minimum, the barcode, author and title fields
2110 need to be filled in. The other fields are ignored if provided.
2112 This method is called by the AcceptItem handler if the C<use_precats>
2113 configuration option is turned on.
2117 sub create_precat_copy {
2119 my $item_info = shift;
2121 my $item = Fieldmapper::asset::copy->new();
2122 $item->barcode($item_info->{barcode});
2123 $item->call_number(OILS_PRECAT_CALL_NUMBER);
2124 $item->dummy_title($item_info->{title});
2125 $item->dummy_author($item_info->{author});
2126 $item->circ_lib($self->{session}->{work_ou}->id());
2127 $item->circulate('t');
2128 $item->holdable('t');
2129 $item->opac_visible('f');
2130 $item->deleted('f');
2131 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2132 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2135 $item->editor($self->{session}->{user}->id());
2136 $item->creator($self->{session}->{user}->id());
2139 # Actually create it:
2141 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2144 $xact = $ses->request(
2145 'open-ils.pcrud.transaction.begin',
2146 $self->{session}->{authtoken}
2148 $item = $ses->request(
2149 'open-ils.pcrud.create.acp',
2150 $self->{session}->{authtoken},
2153 $xact = $ses->request(
2154 'open-ils.pcrud.transaction.commit',
2155 $self->{session}->{authtoken}
2163 'open-ils.pcrud.transaction.rollback',
2164 $self->{session}->{authtoken}
2174 =head2 create_fuller_copy
2177 barcode => '31234003456789',
2178 author => 'Public, John Q.',
2179 title => 'Magnum Opus',
2180 call_number => '005.82',
2181 publisher => 'Brick House',
2182 publication_date => '2014'
2185 $item = $ils->create_fuller_copy($item_info);
2187 Creates a skeletal bibliographic record, call number, and copy for the
2188 incoming item using a hashref with item information in it. At a
2189 minimum, the barcode, author, title, and call_number fields must be
2192 This method is used by the AcceptItem handler if the C<use_precats>
2193 configuration option is NOT set.
2197 sub create_fuller_copy {
2199 my $item_info = shift;
2203 # We do everything in one transaction, because it should be atomic.
2204 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2208 $xact = $ses->request(
2209 'open-ils.pcrud.transaction.begin',
2210 $self->{session}->{authtoken}
2217 # The rest depends on there being a transaction.
2220 # Create the MARC record.
2221 my $record = MARC::Record->new();
2222 $record->encoding('UTF-8');
2223 $record->leader('00881nam a2200193 4500');
2224 my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
2226 push(@fields, MARC::Field->new('005', $datespec));
2227 push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
2228 push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
2229 # Publisher is a little trickier:
2230 if ($item_info->{publisher}) {
2231 my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
2232 $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
2233 push(@fields, $pub);
2235 # We have no idea if the author is personal corporate or something else, so we use a 720.
2236 push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
2237 $record->append_fields(@fields);
2238 my $marc = clean_marc($record);
2240 # Create the bib object.
2241 my $bib = Fieldmapper::biblio::record_entry->new();
2242 $bib->creator($self->{session}->{user}->id());
2243 $bib->editor($self->{session}->{user}->id());
2244 $bib->source($self->{bib_source}->id());
2251 $bib = $ses->request(
2252 'open-ils.pcrud.create.bre',
2253 $self->{session}->{authtoken},
2261 'open-ils.pcrud.transaction.rollback',
2262 $self->{session}->{authtoken}
2267 # Create the call number
2270 $acn = Fieldmapper::asset::call_number->new();
2271 $acn->creator($self->{session}->{user}->id());
2272 $acn->editor($self->{session}->{user}->id());
2273 $acn->label($item_info->{call_number});
2274 $acn->record($bib->id());
2275 $acn->owning_lib($self->{session}->{work_ou}->id());
2280 $acn = $ses->request(
2281 'open-ils.pcrud.create.acn',
2282 $self->{session}->{authtoken},
2290 'open-ils.pcrud.transaction.rollback',
2291 $self->{session}->{authtoken}
2299 $item = Fieldmapper::asset::copy->new();
2300 $item->barcode($item_info->{barcode});
2301 $item->call_number($acn->id());
2302 $item->circ_lib($self->{session}->{work_ou}->id);
2303 $item->circulate('t');
2304 if ($self->{config}->{items}->{use_force_holds}) {
2305 $item->holdable('f');
2307 $item->holdable('t');
2309 $item->opac_visible('f');
2310 $item->deleted('f');
2311 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2312 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2315 $item->editor($self->{session}->{user}->id);
2316 $item->creator($self->{session}->{user}->id);
2320 $item = $ses->request(
2321 'open-ils.pcrud.create.acp',
2322 $self->{session}->{authtoken},
2326 # Cross our fingers and commit the work.
2327 $xact = $ses->request(
2328 'open-ils.pcrud.transaction.commit',
2329 $self->{session}->{authtoken}
2336 'open-ils.pcrud.transaction.rollback',
2337 $self->{session}->{authtoken}
2338 )->gather(1) if ($xact);
2344 # We need to disconnect our session.
2347 # Now, we handle our asset stat_cat entries.
2349 # It would be nice to do these in the above transaction, but
2350 # pcrud does not support the ascecm object, yet.
2351 foreach my $entry (@{$self->{stat_cat_entries}}) {
2352 my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2354 $map->stat_cat($entry->stat_cat());
2355 $map->stat_cat_entry($entry->id());
2356 $map->owning_copy($item->id());
2357 # We don't really worry if it succeeds or not.
2360 'open-ils.circ.stat_cat.asset.copy_map.create',
2361 $self->{session}->{authtoken},
2372 $hold = $ils->place_hold($item, $user, $location, $expiration, $org_unit);
2374 This function places a hold on $item for $user for pickup at
2375 $location. If location is not provided or undefined, the user's home
2376 library is used as a fallback.
2378 The $expiration argument is optional and must be a properly formatted
2379 ISO date time. It will be used as the hold expire time, if
2380 provided. Otherwise the system default time will be used.
2382 The $org_unit parameter is only consulted in the event of $item being
2383 a biblio::record_entry object. In which case, it is expected to be
2384 undefined or an actor::org_unit object. If it is present, then its id
2385 and ou_type depth (if the ou_type field is fleshed) will be used to
2386 control the selection ou and selection depth for the hold. This
2387 essentially limits the hold to being filled by copies belonging to the
2388 specified org_unit or its children.
2390 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2391 (biblio::record_entry). The appropriate hold type will be placed
2392 depending on the object.
2394 On success, the method returns the object representing the hold. On
2395 failure, a NCIP::Problem object, describing the failure, is returned.
2403 my $location = shift;
2404 my $expiration = shift;
2405 my $org_unit = shift;
2407 # If $location is undefined, use the user's home_ou, which should
2408 # have been fleshed when the user was retrieved.
2409 $location = $user->home_ou() unless ($location);
2411 # $hold is the hold. $params is for the is_possible check.
2412 my ($hold, $params);
2414 # Prep the hold with fields common to all hold types:
2415 $hold = Fieldmapper::action::hold_request->new();
2416 $hold->isnew(1); # Just to make sure.
2417 $hold->target($item->id());
2418 $hold->usr($user->id());
2419 $hold->pickup_lib($location->id());
2420 $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2421 if (!$user->email()) {
2422 $hold->email_notify('f');
2423 $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2425 $hold->email_notify('t');
2429 $params = { pickup_lib => $location->id(), patronid => $user->id() };
2431 if (ref($item) eq 'Fieldmapper::asset::copy') {
2432 my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2433 $hold->hold_type($type);
2434 $hold->current_copy($item->id());
2435 $params->{hold_type} = $type;
2436 $params->{copy_id} = $item->id();
2437 } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2438 $hold->hold_type('V');
2439 $params->{hold_type} = 'V';
2440 $params->{volume_id} = $item->id();
2441 } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2442 $hold->hold_type('T');
2443 $params->{hold_type} = 'T';
2444 $params->{titleid} = $item->id();
2445 if ($org_unit && ref($org_unit) eq 'Fieldmapper::actor::org_unit') {
2446 $hold->selection_ou($org_unit->id());
2447 $hold->selection_depth($org_unit->ou_type->depth()) if (ref($org_unit->ou_type()));
2451 # Check for a duplicate hold:
2452 my $duplicate = $U->simplereq(
2454 'open-ils.pcrud.search.ahr',
2455 $self->{session}->{authtoken},
2457 hold_type => $hold->hold_type(),
2458 target => $hold->target(),
2459 usr => $hold->usr(),
2460 expire_time => {'>' => 'now'},
2461 cancel_time => undef,
2462 fulfillment_time => undef
2466 return NCIP::Problem->new(
2468 ProblemType => 'Duplicate Request',
2469 ProblemDetail => 'A request for this item already exists for this patron.',
2470 ProblemElement => 'NULL',
2471 ProblemValue => 'NULL'
2476 # Check if the hold is possible:
2477 my $r = $U->simplereq(
2479 'open-ils.circ.title_hold.is_possible',
2480 $self->{session}->{authtoken},
2484 if ($r->{success}) {
2485 $hold = $U->simplereq(
2487 'open-ils.circ.holds.create.override',
2488 $self->{session}->{authtoken},
2492 $hold = $hold->[0] if (ref($hold) eq 'ARRAY');
2493 $hold = _problem_from_event('Request Not Possible', $hold);
2495 # open-ils.circ.holds.create.override returns the id on
2496 # success, so we retrieve the full hold object from the
2497 # database to return it.
2498 $hold = $U->simplereq(
2500 'open-ils.pcrud.retrieve.ahr',
2501 $self->{session}->{authtoken},
2505 } elsif ($r->{last_event}) {
2506 $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2507 } elsif ($r->{textcode}) {
2508 $hold = _problem_from_event('Request Not Possible', $r);
2510 $hold = _problem_from_event('Request Not Possible');
2518 $ils->cancel_hold($hold);
2520 This method cancels the hold argument. It makes no checks on the hold,
2521 so if there are certain conditions that need to be fulfilled before
2522 the hold is canceled, then you must check them before calling this
2525 It returns undef on success or failure. If it fails, you've usually
2526 got bigger problems.
2534 my $r = $U->simplereq(
2536 'open-ils.circ.hold.cancel',
2537 $self->{session}->{authtoken},
2540 'Canceled via NCIPServer'
2548 $ils->delete_copy($copy);
2550 Deletes the copy, and if it is owned by our work_ou and not a precat,
2551 we also delete the volume and bib on which the copy depends.
2559 # Shortcut for ownership checks below.
2560 my $ou_id = $self->{session}->{work_ou}->id();
2562 # First, make sure the copy is not already deleted and we own it.
2563 return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2565 # Indicate we want to delete the copy.
2566 $copy->isdeleted(1);
2568 # Delete the copy using a backend call that will delete the copy,
2569 # the call number, and bib when appropriate.
2570 my $result = $U->simplereq(
2572 'open-ils.cat.asset.copy.fleshed.batch.update.override',
2573 $self->{session}->{authtoken},
2577 # We are currently not checking for succes or failure of the
2578 # above. At some point, someone may want to.
2583 =head2 copy_can_circulate
2585 $can_circulate = $ils->copy_can_circulate($copy);
2587 Check if the copy's location and the copy itself allow
2588 circulation. Return true if they do, and false if they do not.
2592 sub copy_can_circulate {
2596 my $location = $copy->location();
2597 unless (ref($location)) {
2598 $location = $self->retrieve_copy_location($location);
2601 return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2604 =head2 copy_can_fulfill
2606 $can_fulfill = $ils->copy_can_fulfill($copy);
2608 Check if the copy's location and the copy itself allow
2609 holds. Return true if they do, and false if they do not.
2613 sub copy_can_fulfill {
2617 my $location = $copy->location();
2618 unless (ref($location)) {
2619 $location = $self->retrieve_copy_location($location);
2622 return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2625 =head1 OVERRIDDEN PARENT METHODS
2627 =head2 find_user_barcode
2629 We dangerously override our parent's C<find_user_barcode> to return
2630 either the $barcode or a Problem object. In list context the barcode
2631 or problem will be the first argument and the id field, if any, will
2632 be the second. We also add a second, optional, argument to indicate a
2633 default value for the id field in the event of a failure to find
2634 anything at all. (Perl lets us get away with this.)
2638 sub find_user_barcode {
2640 my $request = shift;
2641 my $default = shift;
2644 my $message = $self->parse_request_type($request);
2645 if ($message eq 'LookupUser') {
2646 $default = 'AuthenticationInputData';
2648 $default = 'UserIdentifierValue';
2652 my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2655 $idfield = $default unless ($idfield);
2656 $value = NCIP::Problem->new();
2657 $value->ProblemType('Needed Data Missing');
2658 $value->ProblemDetail('Cannot find user barcode in message.');
2659 $value->ProblemElement($idfield);
2660 $value->ProblemValue('NULL');
2663 return (wantarray) ? ($value, $idfield) : $value;
2666 =head2 find_item_barcode
2668 We do pretty much the same thing as with C<find_user_barcode> for
2669 C<find_item_barcode>.
2673 sub find_item_barcode {
2675 my $request = shift;
2676 my $default = shift || 'ItemIdentifierValue';
2678 my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2681 $idfield = $default unless ($idfield);
2682 $value = NCIP::Problem->new();
2683 $value->ProblemType('Needed Data Missing');
2684 $value->ProblemDetail('Cannot find item barcode in message.');
2685 $value->ProblemElement($idfield);
2686 $value->ProblemValue('NULL');
2689 return (wantarray) ? ($value, $idfield) : $value;
2692 =head2 find_target_via_bibliographic_id
2694 $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2696 Searches for a bibliographic record to put on hold and returns an
2697 appropriate hold target item depending upon what it finds. If an
2698 appropriate, single target cannot be found, it returns an
2699 NCIP::Problem with the problem message.
2701 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2702 identifiers. If nothing is found, this method can return undef. (Gotta
2703 love Perl and untyped/weakly typed languages in general!)
2705 TODO: Figure out how to search OCLC numbers. We probably need to use
2706 "MARC Expert Search" if we don't want to do a JSON query on
2711 sub find_target_via_bibliographic_id {
2713 my @biblio_ids = @_;
2715 # The item that we find:
2718 # Id for our bib in Evergreen:
2721 # First, let's look for a SYSNUMBER:
2723 { ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'SYSNUMBER')
2724 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER')
2729 # BibliographicRecordId can have an AgencyId field if the
2730 # BibliographicRecordIdentifierCode is absent.
2731 if ($idobj->{AgencyId}) {
2732 $bibid = $idobj->{BibliographicRecordIdentifier};
2733 my $locname = $idobj->{AgencyId};
2735 $locname =~ s/^.*://;
2736 $loc = $self->retrieve_org_unit_by_shortname($locname);
2738 } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2739 $bibid = $idobj->{BibliographicRecordIdentifier};
2741 $bibid = $idobj->{BibliographicItemIdentifier};
2743 if ($bibid && $loc) {
2744 $item = $self->_call_number_search($bibid, $loc);
2746 $item = $U->simplereq(
2748 'open-ils.pcrud.retrieve.bre',
2749 $self->{session}->{authtoken},
2753 # Check if item is deleted so we'll look for more
2755 undef($item) if ($item && $U->is_true($item->deleted()));
2758 # Build an array of id objects based on the other identifier fields.
2761 ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISBN')
2762 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISBN')
2763 || ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISSN')
2764 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISSN')
2768 my $stashed_problem;
2769 # Reuse $idobj from above.
2770 foreach $idobj (@idobjs) {
2771 my ($idvalue, $idtype, $idfield);
2772 if ($_->{BibliographicItemIdentifier}) {
2773 $idvalue = $_->{BibliographicItemIdentifier};
2774 $idtype = $_->{BibliographicItemIdentifierCode};
2775 $idfield = 'BibliographicItemIdentifier';
2777 $idvalue = $_->{BibliographicRecordIdentifier};
2778 $idtype = $_->{BibliographicRecordIdentifierCode};
2779 $idfield = 'BibliographicRecordIdentifier';
2781 $item = $self->_bib_search($idvalue, $idtype);
2782 if (ref($item) eq 'NCIP::Problem') {
2783 $stashed_problem = $item unless($stashed_problem);
2784 $stashed_problem->ProblemElement($idfield);
2789 $item = $stashed_problem if (!$item && $stashed_problem);
2795 =head2 find_location_failover
2797 $location = $ils->find_location_failover($location, $request, $message);
2799 Attempts to retrieve an org_unit by shortname from the passed in
2800 $location. If that fails, $request and $message are used to lookup
2801 the ToAgencyId/AgencyId field and that is used. Returns an org_unit
2802 as retrieved by retrieve_org_unit_by_shortname if successful and undef
2807 sub find_location_failover {
2808 my ($self, $location, $request, $message) = @_;
2809 if ($request && !$message) {
2810 $message = $self->parse_request_type($request);
2814 # Because Auto-Graphics. (This should be configured somehow.)
2815 $location =~ s/^[^-]+-//;
2816 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2818 if ($request && $message && !$org_unit) {
2819 $location = $request->{$message}->{InitiationHeader}->{ToAgencyId}->{AgencyId};
2821 # Because Auto-Graphics. (This should be configured somehow.)
2822 $location =~ s/^[^-]+-//;
2823 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2830 # private subroutines not meant to be used directly by subclasses.
2831 # Most have to do with setup and/or state checking of implementation
2834 # Find, load, and parse our configuration file:
2838 # Find the configuration file via variables:
2839 my $file = OILS_NCIP_CONFIG_DEFAULT;
2840 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2842 $self->{config} = XMLin($file, NormaliseSpace => 2,
2843 ForceArray => ['block_profile', 'stat_cat_entry']);
2846 # Bootstrap OpenSRF::System and load the IDL.
2850 my $bootstrap_config = $self->{config}->{bootstrap};
2851 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2853 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2854 Fieldmapper->import(IDL => $idl);
2857 # Login and then initialize some object data based on the
2862 # Login to Evergreen.
2865 # Load the barred groups as pgt objects into a blocked_profiles
2867 $self->{blocked_profiles} = [];
2868 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2871 $pgt = $U->simplereq(
2873 'open-ils.pcrud.retrieve.pgt',
2874 $self->{session}->{authtoken},
2878 $pgt = $U->simplereq(
2880 'open-ils.pcrud.search.pgt',
2881 $self->{session}->{authtoken},
2885 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2888 # Load the bib source if we're not using precats.
2889 unless ($self->{config}->{items}->{use_precats}) {
2890 # Retrieve the default
2891 $self->{bib_source} = $U->simplereq(
2893 'open-ils.pcrud.retrieve.cbs',
2894 $self->{session}->{authtoken},
2895 BIB_SOURCE_DEFAULT);
2896 my $data = $self->{config}->{items}->{bib_source};
2898 $data = $data->[0] if (ref($data) eq 'ARRAY');
2901 $result = $U->simplereq(
2903 'open-ils.pcrud.retrieve.cbs',
2904 $self->{session}->{authtoken},
2908 $result = $U->simplereq(
2910 'open-ils.pcrud.search.cbs',
2911 $self->{session}->{authtoken},
2915 $self->{bib_source} = $result if ($result);
2919 # Load the required asset.stat_cat_entries:
2920 $self->{stat_cat_entries} = [];
2921 # First, make a regex for our ou and ancestors:
2922 my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2923 my $re = qr/(?:$ancestors)/;
2924 # Get the uniq stat_cat ids from the configuration:
2925 my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2926 # Retrieve all of the fleshed stat_cats and entries for the above.
2927 my $stat_cats = $U->simplereq(
2929 'open-ils.circ.stat_cat.asset.retrieve.batch',
2930 $self->{session}->{authtoken},
2933 foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2934 # Must have the stat_cat attr and the name, so we must have a
2936 next unless(ref $entry);
2937 my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2938 push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2942 # Search asset.call_number by a bre.id and location object. Return the
2943 # "closest" call_number if found, undef otherwise.
2944 sub _call_number_search {
2947 my $location = shift;
2949 # At some point, this should be smarter, and we should retrieve
2950 # ancestors and descendants and search with a JSON query or some
2951 # such with results ordered by proximity to the original location,
2952 # but I don't have time to implement that right now.
2953 my $acn = $U->simplereq(
2955 'open-ils.pcrud.search.acn',
2956 $self->{session}->{authtoken},
2957 {record => $bibid, owning_lib => $location->id()}
2963 # Do a multiclass.query to search for items by isbn or issn.
2966 my $idvalue = shift;
2970 my $result = $U->simplereq(
2972 'open-ils.search.biblio.multiclass',
2973 {searches => {lc($idtype) => $idvalue}}
2976 if ($result && $result->{count}) {
2977 if ($result->{count} > 1) {
2978 $item = NCIP::Problem->new(
2980 ProblemType => 'Non-Unique Item',
2981 ProblemDetail => 'More than one item matches the request.',
2982 ProblemElement => '',
2983 ProblemValue => $idvalue
2987 my $bibid = $result->{ids}->[0]->[0];
2988 $item = $U->simplereq(
2990 'open-ils.pcrud.retrieve.bre',
2991 $self->{session}->{authtoken},
2999 # Search for holds using the user and copy_details information:
3003 my $copy_details = shift;
3007 # Retrieve all of the user's active holds, and then search them in Perl.
3008 my $holds_list = $U->simplereq(
3010 'open-ils.circ.holds.retrieve',
3011 $self->{session}->{authtoken},
3016 if ($holds_list && @$holds_list) {
3018 # Look for title holds (the most common), first:
3019 my $targetid = $copy_details->{mvr}->doc_id();
3020 @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
3022 # Look for volume holds, the next most common:
3023 $targetid = $copy_details->{volume}->id();
3024 @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
3027 # Look for copy and force holds, the least likely.
3028 $targetid = $copy_details->{copy}->id();
3029 @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
3031 # There should only be 1, at this point, if there are any.
3040 # Standalone, "helper" functions. These do not take an object or
3043 # Check if a user is past their expiration date.
3048 # Users might not expire. If so, they have no expire_date.
3049 if ($user->expire_date()) {
3050 my $expires = DateTime::Format::ISO8601->parse_datetime(
3051 cleanse_ISO8601($user->expire_date())
3053 my $now = DateTime->now()->epoch();
3054 $expired = $now > $expires;
3060 # Creates a NCIP Problem from an event. Takes a string for the problem
3061 # type, the event hashref (or a string to use for the detail), and
3062 # optional arguments for the ProblemElement and ProblemValue fields.
3063 sub _problem_from_event {
3064 my ($type, $evt, $element, $value) = @_;
3070 my ($textcode, $desc);
3072 # Get the textcode, if available. Otherwise, use the ilsevent
3073 # "id," if available.
3074 if ($evt->{textcode}) {
3075 $textcode = $evt->{textcode};
3076 } elsif ($evt->{ilsevent}) {
3077 $textcode = $evt->{ilsevent};
3080 # Get the description. We favor translated descriptions over
3081 # the English in ils_events.xml.
3083 $desc = $evt->{desc};
3086 # Check if $type was set. As an "undocumented" feature, you
3087 # can pass undef, and we'll use the textcode from the event.
3094 # Set the detail from some combination of the above.
3097 } elsif ($textcode eq 'PERM_FAILURE') {
3098 if ($evt->{ilsperm}) {
3099 $detail = "Permission denied: " . $evt->{ilsperm};
3100 $detail =~ s/\.override$//;
3102 } elsif ($textcode) {
3103 $detail = "ILS returned $textcode error.";
3105 $detail = 'Detail not available.';
3112 return NCIP::Problem->new(
3114 ProblemType => ($type) ? $type : 'Temporary Processing Failure',
3115 ProblemDetail => ($detail) ? $detail : 'Detail not available.',
3116 ProblemElement => ($element) ? $element : 'NULL',
3117 ProblemValue => ($value) ? $value : 'NULL'
3122 # "Fix" dates for output so they validate against the schema
3125 my $out = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($date));
3126 $out->set_time_zone('UTC');
3127 return $out->iso8601();