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;
55 use NCIP::Item::OptionalFields;
56 use NCIP::Item::BibliographicDescription;
57 use NCIP::Item::BibliographicItemId;
58 use NCIP::Item::BibliographicRecordId;
59 use NCIP::Item::Description;
61 # Inherit from NCIP::ILS.
62 use parent qw(NCIP::ILS);
66 Evergreen - Evergreen driver for NCIPServer
70 my $ils = NCIP::ILS::Evergreen->new(name => $config->{NCIP.ils.value});
74 NCIP::ILS::Evergreen is the default driver for Evergreen and
75 NCIPServer. It was initially developed to work with Auto-Graphics'
76 SHAREit software using a subset of an unspecified ILL/DCB profile.
80 # Default values we define for things that might be missing in our
81 # runtime environment or configuration file that absolutely must have
84 # OILS_NCIP_CONFIG_DEFAULT is the default location to find our
85 # driver's configuration file. This location can be overridden by
86 # setting the path in the OILS_NCIP_CONFIG environment variable.
88 # BIB_SOURCE_DEFAULT is the config.bib_source.id to use when creating
89 # "short" bibs. It is used only if no entry is supplied in the
90 # configuration file. The provided default is 2, the id of the
91 # "System Local" source that comes with a default Evergreen
94 OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
95 BIB_SOURCE_DEFAULT => 2
98 # A common Evergreen code shortcut to use AppUtils:
99 my $U = 'OpenILS::Application::AppUtils';
101 # The usual constructor:
104 $class = ref($class) if (ref $class);
106 # Instantiate our parent with the rest of the arguments. It
107 # creates a blessed hashref.
108 my $self = $class->SUPER::new(@_);
110 # Look for our configuration file, load, and parse it:
113 # Bootstrap OpenSRF and prepare some OpenILS components.
116 # Initialize the rest of our internal state.
122 =head1 HANDLER METHODS
126 $ils->lookupuser($request);
128 Processes a LookupUser request.
136 # Check our session and login if necessary.
137 $self->login() unless ($self->checkauth());
139 my $message_type = $self->parse_request_type($request);
141 # Let's go ahead and create our response object. We need this even
142 # if there is a problem.
143 my $response = NCIP::Response->new({type => $message_type . "Response"});
144 $response->header($self->make_header($request));
146 # Need to parse the request object to get the user barcode.
147 my ($barcode, $idfield) = $self->find_user_barcode($request);
149 # If we did not find a barcode, then report the problem.
150 if (ref($barcode) eq 'NCIP::Problem') {
151 $response->problem($barcode);
155 # Look up our patron by barcode:
156 my $user = $self->retrieve_user_by_barcode($barcode, $idfield);
157 if (ref($user) eq 'NCIP::Problem') {
158 $response->problem($user);
162 # We got the information, so lets fill in our userdata.
163 my $userdata = NCIP::User->new();
165 # Make an array of the user's active barcodes.
167 foreach my $card (@{$user->cards()}) {
168 if ($U->is_true($card->active())) {
169 my $id = NCIP::User::Id->new({
170 UserIdentifierType => 'Barcode',
171 UserIdentifierValue => $card->barcode()
176 $userdata->UserId($ids);
178 # Check if they requested any optional fields and return those.
179 my $elements = $request->{$message_type}->{UserElementType};
181 $elements = [$elements] unless (ref $elements eq 'ARRAY');
182 my $optionalfields = $self->handle_user_elements($user, $elements);
183 $userdata->UserOptionalFields($optionalfields);
186 $response->data($userdata);
193 $ils->acceptitem($request);
195 Processes an AcceptItem request.
203 # Check our session and login if necessary.
204 $self->login() unless ($self->checkauth());
206 # Common preparation.
207 my $message = $self->parse_request_type($request);
208 my $response = NCIP::Response->new({type => $message . 'Response'});
209 $response->header($self->make_header($request));
211 # We only accept holds for the time being.
212 if ($request->{$message}->{RequestedActionType} !~ /^hold\w/i) {
213 # We need the item id or we can't do anything at all.
214 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
215 if (ref($item_barcode) eq 'NCIP::Problem') {
216 $response->problem($item_barcode);
220 # We need to find a patron barcode or we can't look anyone up
222 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request, 'UserIdentifierValue');
223 if (ref($user_barcode) eq 'NCIP::Problem') {
224 $response->problem($user_barcode);
227 # Look up our patron by barcode:
228 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
229 if (ref($user) eq 'NCIP::Problem') {
230 $response->problem($user);
233 # We're doing patron checks before looking for bibliographic
234 # information and creating the item because problems with the
235 # patron are more likely to occur.
236 my $problem = $self->check_user_for_problems($user, 'HOLD');
238 $response->problem($problem);
242 # Check if the item barcode already exists:
243 my $item = $self->retrieve_copy_details_by_barcode($item_barcode);
245 # What to do here was not defined in the
246 # specification. Since the copies that we create this way
247 # should get deleted when checked in, it would be an error
248 # if we try to create another one. It means that something
249 # has gone wrong somewhere.
253 ProblemType => 'Duplicate Item',
254 ProblemDetail => "Item with barcode $item_barcode already exists.",
255 ProblemElement => $item_idfield,
256 ProblemValue => $item_barcode
263 # Now, we have to create our new copy and/or bib and call number.
265 # First, we have to gather the necessary information from the
266 # request. Store in a hashref for convenience. We may write a
267 # method to get this information in the future if we find we
268 # need it in other handlers. Such a function would be a
269 # candidate to go into our parent, NCIP::ILS.
271 barcode => $item_barcode,
272 call_number => $request->{$message}->{ItemOptionalFields}->{ItemDescription}->{CallNumber},
273 title => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Author},
274 author => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Title},
275 publisher => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Publisher},
276 publication_date => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{PublicationDate},
277 medium => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{MediumType},
278 electronic => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{ElectronicResource}
281 if ($self->{config}->{items}->{use_precats}) {
282 # We only need to create a precat copy.
283 $item = $self->create_precat_copy($item_info);
285 # We have to create a "partial" bib record, a call number and a copy.
286 $item = $self->create_fuller_copy($item_info);
289 # If we failed to create the copy, report a problem.
293 ProblemType => 'Temporary Processing Failure',
294 ProblemDetail => 'Failed to create the item in the system',
295 ProblemElement => $item_idfield,
296 ProblemValue => $item_barcode
302 # We try to find the pickup location in our database. It's OK
303 # if it does not exist, the user's home library will be used
305 my $location = $request->{$message}->{PickupLocation};
307 $location = $self->retrieve_org_unit_by_shortname($location);
310 # Now, we place the hold on the newly created copy on behalf
311 # of the patron retrieved above.
312 my $hold = $self->place_hold($item, $user, $location);
313 if (ref($hold) eq 'NCIP::Problem') {
314 $response->problem($hold);
318 # We return the RequestId and optionally, the ItemID. We'll
319 # just return what was sent to us, since we ignored all of it
322 $data->{RequestId} = NCIP::RequestId->new(
324 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
325 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
326 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
329 $data->{ItemId} = NCIP::Item::Id->new(
331 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
332 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
333 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
336 $response->data($data);
339 my $problem = NCIP::Problem->new();
340 $problem->ProblemType('Unauthorized Combination Of Element Values For System');
341 $problem->ProblemDetail('We only support Hold For Pickup');
342 $problem->ProblemElement('RequestedActionType');
343 $problem->ProblemValue($request->{$message}->{RequestedActionType});
344 $response->problem($problem);
352 $response = $ils->checkinitem($request);
354 Checks the item in if we can find the barcode in the message. It
355 returns problems if it cannot find the item in the system or if the
356 item is not checked out.
358 It could definitely use some more brains at some point as it does not
359 fully support everything that the standard allows. It also does not
360 really check if the checkin succeeded or not.
368 # Check our session and login if necessary:
369 $self->login() unless ($self->checkauth());
372 my $message = $self->parse_request_type($request);
373 my $response = NCIP::Response->new({type => $message . 'Response'});
374 $response->header($self->make_header($request));
376 # We need the copy barcode from the message.
377 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
378 if (ref($item_barcode) eq 'NCIP::Problem') {
379 $response->problem($item_barcode);
383 # Retrieve the copy details.
384 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
386 # Return an Unknown Item problem unless we find the copy.
390 ProblemType => 'Unknown Item',
391 ProblemDetail => "Item with barcode $item_barcode is not known.",
392 ProblemElement => $item_idfield,
393 ProblemValue => $item_barcode
400 # Check if a UserId was provided. If so, this is the patron to
401 # whom the copy should be checked out.
403 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
404 # We ignore the problem, because the UserId is optional.
405 if (ref($user_barcode) ne 'NCIP::Problem') {
406 $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
407 # We don't ignore a problem here, however.
408 if (ref($user) eq 'NCIP::Problem') {
409 $response->problem($user);
415 my $copy = $details->{copy};
417 # Look for a circulation and examine its information:
418 my $circ = $details->{circ};
420 # Check the circ details to see if the copy is checked out and, if
421 # the patron was provided, that it is checked out to the patron in
422 # question. We also verify the copy ownership and circulation
424 my $problem = $self->check_circ_details($circ, $copy, $user);
426 # We need to fill in some information, however.
427 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
428 $problem->ProblemValue($user_barcode);
429 $problem->ProblemElement($user_idfield);
430 } elsif (!$problem->ProblemElement()) {
431 $problem->ProblemElement($item_idfield);
433 $response->problem($problem);
437 # Checkin parameters. We want to skip hold targeting or making
438 # transits, to force the checkin despite the copy status, as
439 # well as void overdues.
441 copy_barcode => $copy->barcode(),
446 my $result = $U->simplereq(
448 'open-ils.circ.checkin.override',
449 $self->{session}->{authtoken},
452 if (ref($result) eq 'ARRAY') {
453 $result = $result->[0];
455 if ($result->{textcode} eq 'SUCCESS') {
456 # Delete the copy. Since delete_copy checks ownership
457 # before attempting to delete the copy, we don't bother
458 # checking who owns it.
459 $self->delete_copy($copy);
460 # We need the circulation user for the information below, so we retrieve it.
461 my $circ_user = $self->retrieve_user_by_id($circ->usr());
463 ItemId => NCIP::Item::Id->new(
465 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
466 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
467 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
470 UserId => NCIP::User::Id->new(
472 UserIdentifierType => 'Barcode Id',
473 UserIdentifierValue => $circ_user->card->barcode()
478 # Look for UserElements requested and add it to the response:
479 my $elements = $request->{$message}->{UserElementType};
481 $elements = [$elements] unless (ref $elements eq 'ARRAY');
482 my $optionalfields = $self->handle_user_elements($circ_user, $elements);
483 $data->{UserOptionalFields} = $optionalfields;
485 $elements = $request->{$message}->{ItemElementType};
487 $elements = [$elements] unless (ref $elements eq 'ARRAY');
488 my $optionalfields = $self->handle_item_elements($copy, $elements);
489 $data->{ItemOptionalFields} = $optionalfields;
492 $response->data($data);
494 # At some point in the future, we should probably check if
495 # they requested optional user or item elements and return
496 # those. For the time being, we ignore those at the risk of
497 # being considered non-compliant.
499 $response->problem(_problem_from_event('Checkin Failed', $result));
507 $response = $ils->renewitem($request);
509 Handle the RenewItem message.
517 # Check our session and login if necessary:
518 $self->login() unless ($self->checkauth());
521 my $message = $self->parse_request_type($request);
522 my $response = NCIP::Response->new({type => $message . 'Response'});
523 $response->header($self->make_header($request));
525 # We need the copy barcode from the message.
526 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
527 if (ref($item_barcode) eq 'NCIP::Problem') {
528 $response->problem($item_barcode);
532 # Retrieve the copy details.
533 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
535 # Return an Unknown Item problem unless we find the copy.
539 ProblemType => 'Unknown Item',
540 ProblemDetail => "Item with barcode $item_barcode is not known.",
541 ProblemElement => $item_idfield,
542 ProblemValue => $item_barcode
549 # User is required for RenewItem.
550 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
551 if (ref($user_barcode) eq 'NCIP::Problem') {
552 $response->problem($user_barcode);
555 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
556 if (ref($user) eq 'NCIP::Problem') {
557 $response->problem($user);
562 my $copy = $details->{copy};
564 # Look for a circulation and examine its information:
565 my $circ = $details->{circ};
567 # Check the circ details to see if the copy is checked out and, if
568 # the patron was provided, that it is checked out to the patron in
569 # question. We also verify the copy ownership and circulation
571 my $problem = $self->check_circ_details($circ, $copy, $user);
573 # We need to fill in some information, however.
574 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
575 $problem->ProblemValue($user_barcode);
576 $problem->ProblemElement($user_idfield);
577 } elsif (!$problem->ProblemElement()) {
578 $problem->ProblemElement($item_idfield);
580 $response->problem($problem);
584 # Check if user is blocked from renewals:
585 $problem = $self->check_user_for_problems($user, 'RENEW');
587 # Replace the ProblemElement and ProblemValue fields.
588 $problem->ProblemElement($user_idfield);
589 $problem->ProblemValue($user_barcode);
590 $response->problem($problem);
594 # Check if the duration rule allows renewals. It should have been
595 # fleshed during the copy details retrieve.
596 my $rule = $circ->duration_rule();
597 unless (ref($rule)) {
598 $rule = $U->simplereq(
600 'open-ils.pcrud.retrieve.crcd',
601 $self->{session}->{authtoken},
605 if ($rule->max_renewals() < 1) {
609 ProblemType => 'Item Not Renewable',
610 ProblemDetail => 'Item may not be renewed.',
611 ProblemElement => $item_idfield,
612 ProblemValue => $item_barcode
619 # Check if there are renewals remaining on the latest circ:
620 if ($circ->renewal_remaining() < 1) {
624 ProblemType => 'Maximum Renewals Exceeded',
625 ProblemDetail => 'Renewal cannot proceed because the User has already renewed the Item the maximum number of times permitted.',
626 ProblemElement => $item_idfield,
627 ProblemValue => $item_barcode
634 # Now, we attempt the renewal. If it fails, we simply say that the
635 # user is not allowed to renew this item, without getting into
639 patron_id => $user->id(),
642 my $r = $U->simplereq(
644 'open-ils.circ.renew.override',
645 $self->{session}->{authtoken},
649 # We only look at the first one, since more than one usually means
651 if (ref($r) eq 'ARRAY') {
654 if ($r->{textcode} ne 'SUCCESS') {
655 $problem = _problem_from_event('Renewal Failed', $r);
656 $response->problem($problem);
659 ItemId => NCIP::Item::Id->new(
661 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
662 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
663 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
666 UserId => NCIP::User::Id->new(
668 UserIdentifierType => 'Barcode Id',
669 UserIdentifierValue => $user->card->barcode()
673 # We need to retrieve the copy details again to refresh our
674 # circ information to get the new due date.
675 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
676 $circ = $details->{circ};
677 my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
678 $due->set_time_zone('UTC');
679 $data->{DateDue} = $due->iso8601();
681 # Look for UserElements requested and add it to the response:
682 my $elements = $request->{$message}->{UserElementType};
684 $elements = [$elements] unless (ref $elements eq 'ARRAY');
685 my $optionalfields = $self->handle_user_elements($user, $elements);
686 $data->{UserOptionalFields} = $optionalfields;
688 $elements = $request->{$message}->{ItemElementType};
690 $elements = [$elements] unless (ref $elements eq 'ARRAY');
691 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
692 $data->{ItemOptionalFields} = $optionalfields;
695 $response->data($data);
698 # At some point in the future, we should probably check if
699 # they requested optional user or item elements and return
700 # those. For the time being, we ignore those at the risk of
701 # being considered non-compliant.
708 $response = $ils->checkoutitem($request);
710 Handle the Checkoutitem message.
718 # Check our session and login if necessary:
719 $self->login() unless ($self->checkauth());
722 my $message = $self->parse_request_type($request);
723 my $response = NCIP::Response->new({type => $message . 'Response'});
724 $response->header($self->make_header($request));
726 # We need the copy barcode from the message.
727 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
728 if (ref($item_barcode) eq 'NCIP::Problem') {
729 $response->problem($item_barcode);
733 # Retrieve the copy details.
734 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
736 # Return an Unknown Item problem unless we find the copy.
740 ProblemType => 'Unknown Item',
741 ProblemDetail => "Item with barcode $item_barcode is not known.",
742 ProblemElement => $item_idfield,
743 ProblemValue => $item_barcode
750 # User is required for CheckOutItem.
751 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
752 if (ref($user_barcode) eq 'NCIP::Problem') {
753 $response->problem($user_barcode);
756 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
757 if (ref($user) eq 'NCIP::Problem') {
758 $response->problem($user);
763 my $copy = $details->{copy};
765 # Check if the copy can circulate.
766 unless ($self->copy_can_circulate($copy)) {
770 ProblemType => 'Item Does Not Circulate',
771 ProblemDetail => "Item with barcode $item_barcode does not circulate.",
772 ProblemElement => $item_idfield,
773 ProblemValue => $item_barcode
780 # Look for a circulation and examine its information:
781 my $circ = $details->{circ};
783 # Check if the item is already checked out.
784 if ($circ && !$circ->checkin_time()) {
788 ProblemType => 'Item Already Checked Out',
789 ProblemDetail => "Item with barcode $item_barcode is already checked out.",
790 ProblemElement => $item_idfield,
791 ProblemValue => $item_barcode
798 # Check if user is blocked from circulation:
799 my $problem = $self->check_user_for_problems($user, 'CIRC');
801 # Replace the ProblemElement and ProblemValue fields.
802 $problem->ProblemElement($user_idfield);
803 $problem->ProblemValue($user_barcode);
804 $response->problem($problem);
808 # Now, we attempt the check out. If it fails, we simply say that
809 # the user is not allowed to check out this item, without getting
813 patron_id => $user->id(),
815 my $r = $U->simplereq(
817 'open-ils.circ.checkout.full.override',
818 $self->{session}->{authtoken},
822 # We only look at the first one, since more than one usually means
824 if (ref($r) eq 'ARRAY') {
827 if ($r->{textcode} ne 'SUCCESS') {
828 $problem = _problem_from_event('Check Out Failed', $r);
829 $response->problem($problem);
832 ItemId => NCIP::Item::Id->new(
834 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
835 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
836 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
839 UserId => NCIP::User::Id->new(
841 UserIdentifierType => 'Barcode Id',
842 UserIdentifierValue => $user->card->barcode()
846 # We need to retrieve the copy details again to refresh our
847 # circ information to get the due date.
848 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
849 $circ = $details->{circ};
850 my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
851 $due->set_time_zone('UTC');
852 $data->{DateDue} = $due->iso8601();
854 # Look for UserElements requested and add it to the response:
855 my $elements = $request->{$message}->{UserElementType};
857 $elements = [$elements] unless (ref $elements eq 'ARRAY');
858 my $optionalfields = $self->handle_user_elements($user, $elements);
859 $data->{UserOptionalFields} = $optionalfields;
861 $elements = $request->{$message}->{ItemElementType};
863 $elements = [$elements] unless (ref $elements eq 'ARRAY');
864 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
865 $data->{ItemOptionalFields} = $optionalfields;
868 $response->data($data);
871 # At some point in the future, we should probably check if
872 # they requested optional user or item elements and return
873 # those. For the time being, we ignore those at the risk of
874 # being considered non-compliant.
881 $response = $ils->requestitem($request);
883 Handle the NCIP RequestItem message.
890 # Check our session and login if necessary:
891 $self->login() unless ($self->checkauth());
894 my $message = $self->parse_request_type($request);
895 my $response = NCIP::Response->new({type => $message . 'Response'});
896 $response->header($self->make_header($request));
898 # Because we need to have a user to place a hold, because the user
899 # is likely to have problems, and because getting the item
900 # information for the hold is trickier than getting the user
901 # information, we'll do the user first and short circuit out of
902 # the function if there is a problem with the user.
903 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
904 if (ref($user_barcode) eq 'NCIP::Problem') {
905 $response->problem($user_barcode);
908 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
909 if (ref($user) eq 'NCIP::Problem') {
910 $response->problem($user);
913 my $problem = $self->check_user_for_problems($user, 'HOLD');
915 $response->problem($problem);
919 # RequestItem is a blast. We need to check if we have a copy
920 # barcode and/or if we have BibliographicIds. If we have both or
921 # either, we then need to figure out what we're placing the hold
922 # on, a copy, a volume or a bib. We don't currently do part holds,
923 # but maybe we should some day. We can also be sent more than 1
924 # BibliographicId, so we look for certain identifiers first, and
925 # then others in decreasing preference: SYSNUMBER, ISBN, and ISSN.
927 # Not to mention that there are two kinds of BibliographicId field
928 # with different field names, and both can be intermixed in an
929 # incoming message! (I just /love/ this nonsense.)
931 # This here is the thing we're going to put on hold:
934 # We need copy details if we find in a couple of places below.
937 # We need the copy barcode from the message.
938 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
939 if (ref($item_barcode) ne 'NCIP::Problem') {
940 # Retrieve the copy details.
941 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
942 unless ($copy_details) {
943 # Return an Unknown Item problem unless we find the copy.
947 ProblemType => 'Unknown Item',
948 ProblemDetail => "Item with barcode $item_barcode is not known.",
949 ProblemElement => $item_idfield,
950 ProblemValue => $item_barcode
956 $item = $copy_details->{volume}; # We place a volume hold.
959 # We weren't given copy information to target, or we can't find
960 # it, so we need to look for a target via BibliographicId.
962 my @biblio_ids = $self->find_bibliographic_ids($request);
964 $item = $self->find_target_via_bibliographic_id(@biblio_ids);
968 # If we don't have an item, then blow up with a problem that may
969 # have been set when we went looking for the ItemId.
971 if (ref($item_barcode) eq 'NCIP::Problem') {
972 $response->problem($item_barcode);
977 ProblemType => 'Request Item Not Found',
978 ProblemDetail => 'Unable to determine the item to request from input message.',
979 ProblemElement => 'NULL',
980 ProblemValue => 'NULL'
986 } elsif (ref($item) eq 'NCIP::Problem') {
987 $response->problem($item);
991 # See if we were given a PickupLocation.
993 if ($request->{$message}->{PickupLocation}) {
994 my $loc = $request->{$message}->{PickupLocation};
995 $loc =~ s/^.*://; # strip everything up to the last
996 # semi-colon, if any.
997 $location = $self->retrieve_org_unit_by_shortname($loc);
1000 # Look for a NeedBeforeDate to use as expiration...
1001 my $hold_expiration = $request->{$message}->{NeedBeforeDate};
1004 my $hold = $self->place_hold($item, $user, $location, $hold_expiration);
1005 if (ref($hold) eq 'NCIP::Problem') {
1006 $response->problem($hold);
1009 RequestId => NCIP::RequestId->new(
1010 RequestIdentifierType => 'SYSNUMBER',
1011 RequestIdentifierValue => $hold->id()
1013 UserId => NCIP::User::Id->new(
1015 UserIdentifierType => 'Barcode Id',
1016 UserIdentifierValue => $user->card->barcode()
1019 RequestType => $request->{$message}->{RequestType},
1020 RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1022 # Look for UserElements requested and add it to the response:
1023 my $elements = $request->{$message}->{UserElementType};
1025 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1026 my $optionalfields = $self->handle_user_elements($user, $elements);
1027 $data->{UserOptionalFields} = $optionalfields;
1029 $elements = $request->{$message}->{ItemElementType};
1030 if ($elements && $copy_details) {
1031 $elements = [$elements] unless (ref($elements) eq 'ARRAY');
1032 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1033 $data->{ItemOptionalFields} = $optionalfields;
1036 $response->data($data);
1042 =head2 cancelrequestitem
1044 $response = $ils->cancelrequestitem($request);
1046 Handle the NCIP CancelRequestItem message.
1050 sub cancelrequestitem {
1052 my $request = shift;
1053 # Check our session and login if necessary:
1054 $self->login() unless ($self->checkauth());
1057 my $message = $self->parse_request_type($request);
1058 my $response = NCIP::Response->new({type => $message . 'Response'});
1059 $response->header($self->make_header($request));
1061 # UserId is required by the standard, but we might not really need it.
1062 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1063 if (ref($user_barcode) eq 'NCIP::Problem') {
1064 $response->problem($user_barcode);
1067 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1068 if (ref($user) eq 'NCIP::Problem') {
1069 $response->problem($user);
1073 # See if we got a ItemId and a barcode:
1075 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1076 if (ref($item_barcode) ne 'NCIP::Problem') {
1077 # Retrieve the copy details.
1078 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1079 unless ($copy_details) {
1080 # Return an Unknown Item problem unless we find the copy.
1084 ProblemType => 'Unknown Item',
1085 ProblemDetail => "Item with barcode $item_barcode is not known.",
1086 ProblemElement => $item_idfield,
1087 ProblemValue => $item_barcode
1095 # See if we got a RequestId:
1097 if ($request->{$message}->{RequestId}) {
1098 $requestid = NCIP::RequestId->new(
1100 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1101 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1102 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1107 # Just a note: In the below, we cannot rely on the hold or transit
1108 # fields of the copy_details, even if we have retrieved it. This
1109 # is because that hold and transit may not be the ones that we're
1110 # looking for, i.e. they could be for another patron, etc.
1112 # See if we can find the hold:
1115 $hold = $U->simplereq(
1117 'open-ils.pcrud.retrieve.ahr',
1118 $self->{session}->{authtoken},
1119 $requestid->{RequestIdentifierValue},
1120 {flesh => 1, flesh_fields => {ahr => ['transit']}}
1123 # Report a problem that we couldn't find a hold by that id.
1127 ProblemType => 'Unknown Request',
1128 ProblemDetail => 'No request with this identifier found',
1129 ProblemElement => 'RequestIdentifierValue',
1130 ProblemValue => $requestid->{RequestIdentifierValue}
1134 } elsif ($hold->cancel_time()) {
1138 ProblemType => 'Request Already Canceled',
1139 ProblemDetail => 'Request has already been canceled',
1140 ProblemElement => 'RequestIdentifierValue',
1141 ProblemValue => $requestid->{RequestIdentifierValue}
1145 } elsif ($hold->transit()) {
1149 ProblemType => 'Request Already Processed',
1150 ProblemDetail => 'Request has already been processed',
1151 ProblemElement => 'RequestIdentifierValue',
1152 ProblemValue => $requestid->{RequestIdentifierValue}
1156 } elsif ($hold->usr() == $user->id()) {
1157 # Check the target matches the copy information, if any,
1158 # that we were given.
1160 if ($copy_details) {
1161 if ($hold->hold_type() eq 'V') {
1162 $obj_id = $copy_details->{volume}->id();
1163 } elsif ($hold->hold_type() eq 'T') {
1164 $obj_id = $copy_details->{mvr}->doc_id();
1165 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1166 $obj_id = $copy_details->{copy}->id();
1169 if ($obj_id && $hold->target() != $obj_id) {
1173 ProblemType => 'Request Not For This Item',
1174 ProblemDetail => "Request is not for this item",
1175 ProblemElement => $item_idfield,
1176 ProblemElement => $item_barcode
1181 $self->cancel_hold($hold);
1183 RequestId => $requestid,
1184 UserId => NCIP::User::Id->new(
1186 UserIdentifierType => 'Barcode Id',
1187 UserIdentifierValue => $user->card->barcode()
1191 # Look for UserElements requested and add it to the response:
1192 my $elements = $request->{$message}->{UserElementType};
1194 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1195 my $optionalfields = $self->handle_user_elements($user, $elements);
1196 $data->{UserOptionalFields} = $optionalfields;
1198 $elements = $request->{$message}->{ItemElementType};
1199 if ($elements && $copy_details) {
1200 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1201 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1202 $data->{ItemOptionalFields} = $optionalfields;
1204 $response->data($data);
1207 # Report a problem that the hold is not for this user.
1211 ProblemType => 'Request Not For This User',
1212 ProblemDetail => 'Request is not for this user.',
1213 ProblemElement => $user_idfield,
1214 ProblemValue => $user_barcode
1220 # At this point, we *must have* an ItemId and therefore
1221 # $copy_details, so return the problem from looking up the
1222 # barcode if we don't have $copy_details.
1223 if (!$copy_details) {
1224 $response->problem($item_barcode);
1226 # We have to search for the hold based on the copy details and
1227 # the user. We'll need to search for copy (or force) holds, a
1228 # volume hold, or a title hold.
1229 $hold = $self->_hold_search($user, $copy_details);
1230 if ($hold && $hold->transit()) {
1234 ProblemType => 'Request Already Processed',
1235 ProblemDetail => 'Request has already been processed',
1236 ProblemElement => 'RequestIdentifierValue',
1237 ProblemValue => $requestid->{RequestIdentifierValue}
1242 $self->cancel_hold($hold);
1244 RequestId => NCIP::RequestId->new(
1246 RequestIdentifierType => 'SYSNUMBER',
1247 RequestIdentifierValue => $hold->id()
1250 UserId => NCIP::User::Id->new(
1252 UserIdentifierType => 'Barcode Id',
1253 UserIdentifierValue => $user->card->barcode()
1257 # Look for UserElements requested and add it to the response:
1258 my $elements = $request->{$message}->{UserElementType};
1260 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1261 my $optionalfields = $self->handle_user_elements($user, $elements);
1262 $data->{UserOptionalFields} = $optionalfields;
1264 $elements = $request->{$message}->{ItemElementType};
1265 if ($elements && $copy_details) {
1266 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1267 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1268 $data->{ItemOptionalFields} = $optionalfields;
1270 $response->data($data);
1275 ProblemType => 'Unknown Request',
1276 ProblemDetail => 'No request found for the item and user',
1277 ProblemElement => 'NULL',
1278 ProblemValue => 'NULL'
1289 =head1 METHODS USEFUL to SUBCLASSES
1291 =head2 handle_user_elements
1292 $useroptionalfield = $ils->handle_user_elements($user, $elements);
1294 Returns NCIP::User::OptionalFields for the given user and arrayref of
1299 sub handle_user_elements {
1302 my $elements = shift;
1303 my $optionalfields = NCIP::User::OptionalFields->new();
1305 # First, we'll look for name information.
1306 if (grep {$_ eq 'Name Information'} @$elements) {
1307 my $name = NCIP::StructuredPersonalUserName->new();
1308 $name->Surname($user->family_name());
1309 $name->GivenName($user->first_given_name());
1310 $name->Prefix($user->prefix());
1311 $name->Suffix($user->suffix());
1312 $optionalfields->NameInformation($name);
1315 # Next, check for user address information.
1316 if (grep {$_ eq 'User Address Information'} @$elements) {
1319 # See if the user has any valid, physcial addresses.
1320 foreach my $addr (@{$user->addresses()}) {
1321 next if ($U->is_true($addr->pending()));
1322 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
1323 my $physical = NCIP::StructuredAddress->new();
1324 $physical->Line1($addr->street1());
1325 $physical->Line2($addr->street2());
1326 $physical->Locality($addr->city());
1327 $physical->Region($addr->state());
1328 $physical->PostalCode($addr->post_code());
1329 $physical->Country($addr->country());
1330 $address->PhysicalAddress($physical);
1331 push @$addresses, $address;
1334 # Right now, we're only sharing email address if the user
1335 # has it. We don't share phone numbers.
1336 if ($user->email()) {
1337 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
1338 $address->ElectronicAddress(
1339 NCIP::ElectronicAddress->new({
1340 Type=>'Email Address',
1341 Data=>$user->email()
1344 push @$addresses, $address;
1347 $optionalfields->UserAddressInformation($addresses);
1350 # Check for User Privilege.
1351 if (grep {$_ eq 'User Privilege'} @$elements) {
1352 # Get the user's group:
1353 my $pgt = $U->simplereq(
1355 'open-ils.pcrud.retrieve.pgt',
1356 $self->{session}->{authtoken},
1360 my $privilege = NCIP::User::Privilege->new();
1361 $privilege->AgencyId($user->home_ou->shortname());
1362 $privilege->AgencyUserPrivilegeType($pgt->name());
1363 $privilege->ValidToDate($user->expire_date());
1364 $privilege->ValidFromDate($user->create_date());
1366 my $status = 'Active';
1367 if (_expired($user)) {
1368 $status = 'Expired';
1369 } elsif ($U->is_true($user->barred())) {
1371 } elsif (!$U->is_true($user->active())) {
1372 $status = 'Inactive';
1375 $privilege->UserPrivilegeStatus(
1376 NCIP::User::PrivilegeStatus->new({
1377 UserPrivilegeStatusType => $status
1382 $optionalfields->UserPrivilege([$privilege]);
1386 # Check for Block Or Trap.
1387 if (grep {$_ eq 'Block Or Trap'} @$elements) {
1390 # First, let's check if the profile is blocked from ILL.
1391 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1392 my $block = NCIP::User::BlockOrTrap->new();
1393 $block->AgencyId($user->home_ou->shortname());
1394 $block->BlockOrTrapType('Block Interlibrary Loan');
1395 push @$blocks, $block;
1398 # Next, we loop through the user's standing penalties
1399 # looking for blocks on CIRC, HOLD, and RENEW.
1400 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
1401 foreach my $penalty (@{$user->standing_penalties()}) {
1402 next unless($penalty->standing_penalty->block_list());
1403 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
1404 my $ou = $U->simplereq(
1406 'open-ils.pcrud.retrieve.aou',
1407 $self->{session}->{authtoken},
1408 $penalty->org_unit()
1412 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
1413 my $bot = NCIP::User::BlockOrTrap->new();
1414 $bot->AgencyId($ou->shortname());
1415 $bot->BlockOrTrapType('Block Checkout');
1416 push @$blocks, $bot;
1421 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
1422 my $bot = NCIP::User::BlockOrTrap->new();
1423 $bot->AgencyId($ou->shortname());
1424 $bot->BlockOrTrapType('Block Holds');
1425 push @$blocks, $bot;
1430 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
1431 my $bot = NCIP::User::BlockOrTrap->new();
1432 $bot->AgencyId($ou->shortname());
1433 $bot->BlockOrTrapType('Block Renewals');
1434 push @$blocks, $bot;
1438 # Stop after we report one of each, even if more
1440 last if ($have_circ && $have_renew && $have_hold);
1443 $optionalfields->BlockOrTrap($blocks);
1446 return $optionalfields;
1449 =head2 handle_item_elements
1453 sub handle_item_elements {
1456 my $elements = shift;
1457 my $optionalfields = NCIP::Item::OptionalFields->new();
1459 my $details; # In case we need for more than one.
1461 if (grep {$_ eq 'Bibliographic Description'} @$elements) {
1463 # Check for a precat copy, 'cause it is simple.
1464 if ($copy->dummy_title()) {
1465 $description = NCIP::Item::BibliographicDescription->new();
1466 $description->Title($copy->dummy_title());
1467 $description->Author($copy->dummy_author());
1468 if ($copy->dummy_isbn()) {
1469 $description->BibliographicItemId(
1470 NCIP::Item::BibliographicItemId->new(
1472 BibliographicItemIdentifier => $copy->dummy_isbn(),
1473 BibliographicItemIdentifierCode => 'ISBN'
1479 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1480 $description = NCIP::Item::BibliographicDescription->new();
1481 $description->Title($details->{mvr}->title());
1482 $description->Authort($details->{mvr}->author());
1483 $description->BibliographicRecordId(
1484 NCIP::Item::BibliographicRecordId->new(
1486 BibliographicRecordIdentifier => $details->{mvr}->doc_id(),
1487 BibliographicRecordIdentifierCode => 'SYSNUMBER'
1491 if ($details->{mvr}->publisher()) {
1492 $description->Publisher($details->{mvr}->publisher());
1494 if ($details->{mvr}->pubdate()) {
1495 $description->PublicationDate($details->{mvr}->pubdate());
1497 if ($details->{mvr}->edition()) {
1498 $description->Edition($details->{mvr}->edition());
1501 $optionalfields->BibliographicDescription($description) if ($description);
1504 if (grep {$_ eq 'Item Description'} @$elements) {
1505 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1506 # Call Number is the only field we currently return. We also
1507 # do not attempt to retun a prefix and suffix. Someone else
1508 # can deal with that if they want it.
1509 if ($details->{volume}) {
1510 $optionalfields->ItemDescription(
1511 NCIP::Item::Description->new(
1512 {CallNumber => $details->{volume}->label()}
1518 if (grep {$_ eq 'Circulation Status'} @$elements) {
1519 my $status = $copy->status();
1520 $status = $self->retrieve_copy_status($status) unless (ref($status));
1521 $optionalfields->CirculationStatus($status->name()) if ($status);
1524 if (grep {$_ eq 'Date Due'} @$elements) {
1525 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1526 if ($details->{circ}) {
1527 if (!$details->{circ}->checkin_time()) {
1528 my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($details->{circ}->due_date()));
1529 $due->set_time_zone('UTC');
1530 $optionalfields->DateDue($due->iso8601());
1535 if (grep {$_ eq 'Item Use Restriction Type'} @$elements) {
1536 $optionalfields->ItemUseRestrictionType('None');
1539 if (grep {$_ eq 'Physical Condition'} @$elements) {
1540 $optionalfields->PhysicalCondition(
1541 NCIP::Item::PhysicalCondition->new(
1542 {PhysicalConditionType => 'Unknown'}
1547 return $optionalfields;
1554 Login to Evergreen via OpenSRF. It uses internal state from the
1555 configuration file to login.
1559 # Login via OpenSRF to Evergreen.
1563 # Get the authentication seed.
1564 my $seed = $U->simplereq(
1566 'open-ils.auth.authenticate.init',
1567 $self->{config}->{credentials}->{username}
1572 my $response = $U->simplereq(
1574 'open-ils.auth.authenticate.complete',
1576 username => $self->{config}->{credentials}->{username},
1577 password => md5_hex(
1578 $seed . md5_hex($self->{config}->{credentials}->{password})
1581 workstation => $self->{config}->{credentials}->{workstation}
1585 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1586 $self->{session}->{authtime} = $response->{payload}->{authtime};
1588 # Set/reset the work_ou and user data in case something changed.
1590 # Retrieve the work_ou as an object.
1591 $self->{session}->{work_ou} = $U->simplereq(
1593 'open-ils.pcrud.search.aou',
1594 $self->{session}->{authtoken},
1595 {shortname => $self->{config}->{credentials}->{work_ou}}
1598 # We need the user information in order to do some things.
1599 $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1607 $valid = $ils->checkauth();
1609 Returns 1 if the object a 'valid' authtoken, 0 if not.
1616 # We use AppUtils to do the heavy lifting.
1617 if (defined($self->{session})) {
1618 if ($U->check_user_session($self->{session}->{authtoken})) {
1625 # If we reach here, we don't have a session, so we are definitely
1630 =head2 retrieve_user_by_barcode
1632 $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1634 Do a fleshed retrieve of a patron by barcode. Return the patron if
1635 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1637 The id field argument is used for the ProblemElement field in the
1638 NCIP::Problem object.
1640 An invalid patron is one where the barcode is not found in the
1641 database, the patron is deleted, or the barcode used to retrieve the
1642 patron is not active. The problem element is also returned if an error
1643 occurs during the retrieval.
1647 sub retrieve_user_by_barcode {
1648 my ($self, $barcode, $idfield) = @_;
1649 my $result = $U->simplereq(
1651 'open-ils.actor.user.fleshed.retrieve_by_barcode',
1652 $self->{session}->{authtoken},
1657 # Check for a failure, or a deleted, inactive, or expired user,
1658 # and if so, return empty userdata.
1659 if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1660 || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1662 my $problem = NCIP::Problem->new();
1663 $problem->ProblemType('Unknown User');
1664 $problem->ProblemDetail("User with barcode $barcode unknown");
1665 $problem->ProblemElement($idfield);
1666 $problem->ProblemValue($barcode);
1673 =head2 retrieve_user_by_id
1675 $user = $ils->retrieve_user_by_id($id);
1677 Similar to C<retrieve_user_by_barcode> but takes the user's database
1678 id rather than barcode. This is useful when you have a circulation or
1679 hold and need to get information about the user's involved in the hold
1682 It returns a fleshed user on success or undef on failure.
1686 sub retrieve_user_by_id {
1687 my ($self, $id) = @_;
1689 # Do a fleshed retrieve of the patron, and flesh the fields that
1690 # we would normally use.
1691 my $result = $U->simplereq(
1693 'open-ils.actor.user.fleshed.retrieve',
1694 $self->{session}->{authtoken},
1696 [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1698 # Check for an error.
1699 undef($result) if ($result && $U->event_code($result));
1704 =head2 check_user_for_problems
1706 $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1708 This function checks if a user has a blocked profile or any from a
1709 list of provided blocks. If it does, then a NCIP::Problem object is
1710 returned, otherwise an undefined value is returned.
1712 The list of blocks appears as additional arguments after the user. You
1713 can provide any value(s) that might appear in a standing penalty block
1714 lit in Evergreen. The example above checks for HOLD, CIRC, and
1715 RENEW. Any number of such values can be provided. If none are
1716 provided, the function only checks if the patron's profiles appears in
1717 the object's blocked profiles list.
1719 It stops on the first matching block, if any.
1723 sub check_user_for_problems {
1728 # Fill this in if we have a problem, otherwise just return it.
1731 # First, check the user's profile.
1732 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1733 $problem = NCIP::Problem->new(
1735 ProblemType => 'User Blocked',
1736 ProblemDetail => 'User blocked from inter-library loan',
1737 ProblemElement => 'NULL',
1738 ProblemValue => 'NULL'
1743 # Next, check if the patron has one of the indicated blocks.
1745 foreach my $penalty (@{$user->standing_penalties()}) {
1746 if ($penalty->standing_penalty->block_list()) {
1747 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1748 foreach my $block (@blocks) {
1749 if (grep {$_ =~ /$block/} @pblocks) {
1750 $problem = NCIP::Problem->new(
1752 ProblemType => 'User Blocked',
1753 ProblemDetail => 'User blocked from ' .
1754 ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1755 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1756 ProblemElement => 'NULL',
1757 ProblemValue => 'NULL'
1771 =head2 check_circ_details
1773 $problem = $ils->check_circ_details($circ, $copy, $user);
1775 Checks if we can checkin or renew a circulation. That is, the
1776 circulation is still open (i.e. the copy is still checked out), if we
1777 either own the copy or are the circulation location, and if the
1778 circulation is for the optional $user argument. $circ and $copy are
1779 required. $user is optional.
1781 Returns a problem if any of the above conditions fail. Returns undef
1782 if they pass and we can proceed with the checkin or renewal.
1784 If the failure occurred on the copy-related checks, then the
1785 ProblemElement field will be undefined and needs to be filled in with
1786 the item id field name. If the check for the copy being checked out to
1787 the provided user fails, then both ProblemElement and ProblemValue
1788 fields will be empty and need to be filled in by the caller.
1792 sub check_circ_details {
1793 my ($self, $circ, $copy, $user) = @_;
1795 # Shortcut for the next check.
1796 my $ou_id = $self->{session}->{work_ou}->id();
1798 if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1799 # Item isn't checked out.
1800 return NCIP::Problem->new(
1802 ProblemType => 'Item Not Checked Out',
1803 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1804 ProblemValue => $copy->barcode()
1808 # Get data on the patron who has it checked out.
1809 my $circ_user = $self->retrieve_user_by_id($circ->usr());
1810 if ($user && $circ_user && $user->id() != $circ_user->id()) {
1811 # The ProblemElement and ProblemValue field need to be
1812 # filled in by the caller.
1813 return NCIP::Problem->new(
1815 ProblemType => 'Item Not Checked Out To This User',
1816 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1821 # If we get here, we're good to go.
1825 =head2 retrieve_copy_details_by_barcode
1827 $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1829 Look up and retrieve some copy details by the copy barcode. This
1830 method returns either a hashref with the copy details or undefined if
1831 no copy exists with that barcode or if some error occurs.
1833 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1835 This method differs from C<retrieve_user_by_barcode> in that a copy
1836 cannot be invalid if it exists and it is not always an error if no
1837 copy exists. In some cases, when handling AcceptItem, we might prefer
1838 there to be no copy.
1842 sub retrieve_copy_details_by_barcode {
1844 my $barcode = shift;
1846 my $copy = $U->simplereq(
1848 'open-ils.circ.copy_details.retrieve.barcode',
1849 $self->{session}->{authtoken},
1853 # If $copy is an event, return undefined.
1854 if ($copy && $U->event_code($copy)) {
1861 =head2 retrieve_copy_status
1863 $status = $ils->retrieve_copy_status($id);
1865 Retrive a copy status object by database ID.
1869 sub retrieve_copy_status {
1873 my $status = $U->simplereq(
1875 'open-ils.pcrud.retrieve.ccs',
1876 $self->{session}->{authtoken},
1883 =head2 retrieve_org_unit_by_shortname
1885 $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1887 Retrieves an org. unit from the database by shortname. Returns the
1888 org. unit as a Fieldmapper object or undefined.
1892 sub retrieve_org_unit_by_shortname {
1894 my $shortname = shift;
1896 my $aou = $U->simplereq(
1898 'open-ils.actor.org_unit.retrieve_by_shortname',
1905 =head2 retrieve_copy_location
1907 $location = $ils->retrieve_copy_location($location_id);
1909 Retrieve a copy location based on id.
1913 sub retrieve_copy_location {
1917 my $location = $U->simplereq(
1919 'open-ils.pcrud.retrieve.acpl',
1920 $self->{session}->{authtoken},
1927 =head2 retrieve_biblio_record_entry
1929 $bre = $ils->retrieve_biblio_record_entry($bre_id);
1931 Given a biblio.record_entry.id, this method retrieves a bre object.
1935 sub retrieve_biblio_record_entry {
1939 my $bre = $U->simplereq(
1941 'open-ils.pcrud.retrieve.bre',
1942 $self->{session}->{authtoken},
1949 =head2 create_precat_copy
1952 barcode => '312340123456789',
1953 author => 'Public, John Q.',
1954 title => 'Magnum Opus',
1955 call_number => '005.82',
1956 publisher => 'Brick House',
1957 publication_date => '2014'
1960 $item = $ils->create_precat_copy($item_info);
1963 Create a "precat" copy to use for the incoming item using a hashref of
1964 item information. At a minimum, the barcode, author and title fields
1965 need to be filled in. The other fields are ignored if provided.
1967 This method is called by the AcceptItem handler if the C<use_precats>
1968 configuration option is turned on.
1972 sub create_precat_copy {
1974 my $item_info = shift;
1976 my $item = Fieldmapper::asset::copy->new();
1977 $item->barcode($item_info->{barcode});
1978 $item->call_number(OILS_PRECAT_CALL_NUMBER);
1979 $item->dummy_title($item_info->{title});
1980 $item->dummy_author($item_info->{author});
1981 $item->circ_lib($self->{session}->{work_ou}->id());
1982 $item->circulate('t');
1983 $item->holdable('t');
1984 $item->opac_visible('f');
1985 $item->deleted('f');
1986 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1987 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1990 $item->editor($self->{session}->{user}->id());
1991 $item->creator($self->{session}->{user}->id());
1994 # Actually create it:
1996 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1999 $xact = $ses->request(
2000 'open-ils.pcrud.transaction.begin',
2001 $self->{session}->{authtoken}
2003 $item = $ses->request(
2004 'open-ils.pcrud.create.acp',
2005 $self->{session}->{authtoken},
2008 $xact = $ses->request(
2009 'open-ils.pcrud.transaction.commit',
2010 $self->{session}->{authtoken}
2018 'open-ils.pcrud.transaction.rollback',
2019 $self->{session}->{authtoken}
2029 =head2 create_fuller_copy
2032 barcode => '31234003456789',
2033 author => 'Public, John Q.',
2034 title => 'Magnum Opus',
2035 call_number => '005.82',
2036 publisher => 'Brick House',
2037 publication_date => '2014'
2040 $item = $ils->create_fuller_copy($item_info);
2042 Creates a skeletal bibliographic record, call number, and copy for the
2043 incoming item using a hashref with item information in it. At a
2044 minimum, the barcode, author, title, and call_number fields must be
2047 This method is used by the AcceptItem handler if the C<use_precats>
2048 configuration option is NOT set.
2052 sub create_fuller_copy {
2054 my $item_info = shift;
2058 # We do everything in one transaction, because it should be atomic.
2059 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2063 $xact = $ses->request(
2064 'open-ils.pcrud.transaction.begin',
2065 $self->{session}->{authtoken}
2072 # The rest depends on there being a transaction.
2075 # Create the MARC record.
2076 my $record = MARC::Record->new();
2077 $record->encoding('UTF-8');
2078 $record->leader('00881nam a2200193 4500');
2079 my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
2081 push(@fields, MARC::Field->new('005', $datespec));
2082 push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
2083 push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
2084 # Publisher is a little trickier:
2085 if ($item_info->{publisher}) {
2086 my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
2087 $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
2088 push(@fields, $pub);
2090 # We have no idea if the author is personal corporate or something else, so we use a 720.
2091 push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
2092 $record->append_fields(@fields);
2093 my $marc = clean_marc($record);
2095 # Create the bib object.
2096 my $bib = Fieldmapper::biblio::record_entry->new();
2097 $bib->creator($self->{session}->{user}->id());
2098 $bib->editor($self->{session}->{user}->id());
2099 $bib->source($self->{bib_source}->id());
2106 $bib = $ses->request(
2107 'open-ils.pcrud.create.bre',
2108 $self->{session}->{authtoken},
2116 'open-ils.pcrud.transaction.rollback',
2117 $self->{session}->{authtoken}
2122 # Create the call number
2125 $acn = Fieldmapper::asset::call_number->new();
2126 $acn->creator($self->{session}->{user}->id());
2127 $acn->editor($self->{session}->{user}->id());
2128 $acn->label($item_info->{call_number});
2129 $acn->record($bib->id());
2130 $acn->owning_lib($self->{session}->{work_ou}->id());
2135 $acn = $ses->request(
2136 'open-ils.pcrud.create.acn',
2137 $self->{session}->{authtoken},
2145 'open-ils.pcrud.transaction.rollback',
2146 $self->{session}->{authtoken}
2154 $item = Fieldmapper::asset::copy->new();
2155 $item->barcode($item_info->{barcode});
2156 $item->call_number($acn->id());
2157 $item->circ_lib($self->{session}->{work_ou}->id);
2158 $item->circulate('t');
2159 if ($self->{config}->{items}->{use_force_holds}) {
2160 $item->holdable('f');
2162 $item->holdable('t');
2164 $item->opac_visible('f');
2165 $item->deleted('f');
2166 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2167 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2170 $item->editor($self->{session}->{user}->id);
2171 $item->creator($self->{session}->{user}->id);
2175 $item = $ses->request(
2176 'open-ils.pcrud.create.acp',
2177 $self->{session}->{authtoken},
2181 # Cross our fingers and commit the work.
2182 $xact = $ses->request(
2183 'open-ils.pcrud.transaction.commit',
2184 $self->{session}->{authtoken}
2191 'open-ils.pcrud.transaction.rollback',
2192 $self->{session}->{authtoken}
2193 )->gather(1) if ($xact);
2199 # We need to disconnect our session.
2202 # Now, we handle our asset stat_cat entries.
2204 # It would be nice to do these in the above transaction, but
2205 # pcrud does not support the ascecm object, yet.
2206 foreach my $entry (@{$self->{stat_cat_entries}}) {
2207 my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2209 $map->stat_cat($entry->stat_cat());
2210 $map->stat_cat_entry($entry->id());
2211 $map->owning_copy($item->id());
2212 # We don't really worry if it succeeds or not.
2215 'open-ils.circ.stat_cat.asset.copy_map.create',
2216 $self->{session}->{authtoken},
2227 $hold = $ils->place_hold($item, $user, $location, $expiration);
2229 This function places a hold on $item for $user for pickup at
2230 $location. If location is not provided or undefined, the user's home
2231 library is used as a fallback.
2233 The $expiration argument is optional and must be a properly formatted
2234 ISO date time. It will be used as the hold expire time, if
2235 provided. Otherwise the system default time will be used.
2237 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2238 (biblio::record_entry). The appropriate hold type will be placed
2239 depending on the object.
2241 On success, the method returns the object representing the hold. On
2242 failure, a NCIP::Problem object, describing the failure, is returned.
2250 my $location = shift;
2251 my $expiration = shift;
2253 # If $location is undefined, use the user's home_ou, which should
2254 # have been fleshed when the user was retrieved.
2255 $location = $user->home_ou() unless ($location);
2257 # $hold is the hold. $params is for the is_possible check.
2258 my ($hold, $params);
2260 # Prep the hold with fields common to all hold types:
2261 $hold = Fieldmapper::action::hold_request->new();
2262 $hold->isnew(1); # Just to make sure.
2263 $hold->target($item->id());
2264 $hold->usr($user->id());
2265 $hold->pickup_lib($location->id());
2266 $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2267 if (!$user->email()) {
2268 $hold->email_notify('f');
2269 $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2271 $hold->email_notify('t');
2275 $params = { pickup_lib => $location->id(), patronid => $user->id() };
2277 if (ref($item) eq 'Fieldmapper::asset::copy') {
2278 my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2279 $hold->hold_type($type);
2280 $hold->current_copy($item->id());
2281 $params->{hold_type} = $type;
2282 $params->{copy_id} = $item->id();
2283 } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2284 $hold->hold_type('V');
2285 $params->{hold_type} = 'V';
2286 $params->{volume_id} = $item->id();
2287 } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2288 $hold->hold_type('T');
2289 $params->{hold_type} = 'T';
2290 $params->{titleid} = $item->id();
2293 # Check for a duplicate hold:
2294 my $duplicate = $U->simplereq(
2296 'open-ils.pcrud.search.ahr',
2297 $self->{session}->{authtoken},
2299 hold_type => $hold->hold_type(),
2300 target => $hold->target(),
2301 usr => $hold->usr(),
2302 expire_time => {'>' => 'now'},
2303 cancel_time => undef,
2304 fulfillment_time => undef
2308 return NCIP::Problem->new(
2310 ProblemType => 'Duplicate Request',
2311 ProblemDetail => 'A request for this item already exists for this patron.',
2312 ProblemElement => 'NULL',
2313 ProblemValue => 'NULL'
2318 # Check if the hold is possible:
2319 my $r = $U->simplereq(
2321 'open-ils.circ.title_hold.is_possible',
2322 $self->{session}->{authtoken},
2326 if ($r->{success}) {
2327 $hold = $U->simplereq(
2329 'open-ils.circ.holds.create.override',
2330 $self->{session}->{authtoken},
2333 if (ref($hold) eq 'HASH') {
2334 $hold = _problem_from_event('Request Not Possible', $hold);
2336 } elsif ($r->{last_event}) {
2337 $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2338 } elsif ($r->{textcode}) {
2339 $hold = _problem_from_event('Request Not Possible', $r);
2341 $hold = _problem_from_event('Request Not Possible');
2349 $ils->cancel_hold($hold);
2351 This method cancels the hold argument. It makes no checks on the hold,
2352 so if there are certain conditions that need to be fulfilled before
2353 the hold is canceled, then you must check them before calling this
2356 It returns undef on success or failure. If it fails, you've usually
2357 got bigger problems.
2365 my $r = $U->simplereq(
2367 'open-ils.circ.hold.cancel',
2368 $self->{session}->{authtoken},
2371 'Canceled via NCIPServer'
2379 $ils->delete_copy($copy);
2381 Deletes the copy, and if it is owned by our work_ou and not a precat,
2382 we also delete the volume and bib on which the copy depends.
2390 # Shortcut for ownership checks below.
2391 my $ou_id = $self->{session}->{work_ou}->id();
2393 # First, make sure the copy is not already deleted and we own it.
2394 return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2396 # Indicate we want to delete the copy.
2397 $copy->isdeleted(1);
2399 # Delete the copy using a backend call that will delete the copy,
2400 # the call number, and bib when appropriate.
2401 my $result = $U->simplereq(
2403 'open-ils.cat.asset.copy.fleshed.batch.update.override',
2404 $self->{session}->{authtoken},
2408 # We are currently not checking for succes or failure of the
2409 # above. At some point, someone may want to.
2414 =head2 copy_can_circulate
2416 $can_circulate = $ils->copy_can_circulate($copy);
2418 Check if the copy's location and the copy itself allow
2419 circulation. Return true if they do, and false if they do not.
2423 sub copy_can_circulate {
2427 my $location = $copy->location();
2428 unless (ref($location)) {
2429 $location = $self->retrieve_copy_location($location);
2432 return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2435 =head2 copy_can_fulfill
2437 $can_fulfill = $ils->copy_can_fulfill($copy);
2439 Check if the copy's location and the copy itself allow
2440 holds. Return true if they do, and false if they do not.
2444 sub copy_can_fulfill {
2448 my $location = $copy->location();
2449 unless (ref($location)) {
2450 $location = $self->retrieve_copy_location($location);
2453 return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2456 =head1 OVERRIDDEN PARENT METHODS
2458 =head2 find_user_barcode
2460 We dangerously override our parent's C<find_user_barcode> to return
2461 either the $barcode or a Problem object. In list context the barcode
2462 or problem will be the first argument and the id field, if any, will
2463 be the second. We also add a second, optional, argument to indicate a
2464 default value for the id field in the event of a failure to find
2465 anything at all. (Perl lets us get away with this.)
2469 sub find_user_barcode {
2471 my $request = shift;
2472 my $default = shift;
2475 my $message = $self->parse_request_type($request);
2476 if ($message eq 'LookupUser') {
2477 $default = 'AuthenticationInputData';
2479 $default = 'UserIdentifierValue';
2483 my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2486 $idfield = $default unless ($idfield);
2487 $value = NCIP::Problem->new();
2488 $value->ProblemType('Needed Data Missing');
2489 $value->ProblemDetail('Cannot find user barcode in message.');
2490 $value->ProblemElement($idfield);
2491 $value->ProblemValue('NULL');
2494 return (wantarray) ? ($value, $idfield) : $value;
2497 =head2 find_item_barcode
2499 We do pretty much the same thing as with C<find_user_barcode> for
2500 C<find_item_barcode>.
2504 sub find_item_barcode {
2506 my $request = shift;
2507 my $default = shift || 'ItemIdentifierValue';
2509 my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2512 $idfield = $default unless ($idfield);
2513 $value = NCIP::Problem->new();
2514 $value->ProblemType('Needed Data Missing');
2515 $value->ProblemDetail('Cannot find item barcode in message.');
2516 $value->ProblemElement($idfield);
2517 $value->ProblemValue('NULL');
2520 return (wantarray) ? ($value, $idfield) : $value;
2523 =head2 find_target_via_bibliographic_id
2525 $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2527 Searches for a bibliographic record to put on hold and returns an
2528 appropriate hold target item depending upon what it finds. If an
2529 appropriate, single target cannot be found, it returns an
2530 NCIP::Problem with the problem message.
2532 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2533 identifiers. If nothing is found, this method can return undef. (Gotta
2534 love Perl and untyped/weakly typed languages in general!)
2536 TODO: Figure out how to search OCLC numbers. We probably need to use
2537 "MARC Expert Search" if we don't want to do a JSON query on
2542 sub find_target_via_bibliographic_id {
2544 my @biblio_ids = @_;
2546 # The item that we find:
2549 # Id for our bib in Evergreen:
2552 # First, let's look for a SYSNUMBER:
2554 { ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'SYSNUMBER')
2555 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER')
2560 # BibliographicRecordId can have an AgencyId field if the
2561 # BibliographicRecordIdentifierCode is absent.
2562 if ($idobj->{AgencyId}) {
2563 $bibid = $idobj->{BibliographicRecordIdentifier};
2564 my $locname = $idobj->{AgencyId};
2566 $locname =~ s/.*://;
2567 $loc = $self->retrieve_org_unit_by_shortname($locname);
2569 } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2570 $bibid = $idobj->{BibliographicRecordIdentifierCode}
2572 $bibid = $idobj->{BibliographicItemIdentifierCode}
2574 if ($bibid && $loc) {
2575 $item = $self->_call_number_search($bibid, $loc);
2577 $item = $U->simplereq(
2579 'open-ils.pcrud.retrieve.bre',
2580 $self->{session}->{authtoken},
2584 # Check if item is deleted so we'll look for more
2586 undef($item) if ($item && $U->is_true($item->deleted()));
2589 # Build an array of id objects based on the other identifier fields.
2592 ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISBN')
2593 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISBN')
2594 || ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISSN')
2595 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISSN')
2599 my $stashed_problem;
2600 # Reuse $idobj from above.
2601 foreach $idobj (@idobjs) {
2602 my ($idvalue, $idtype, $idfield);
2603 if ($_->{BibliographicItemIdentifier}) {
2604 $idvalue = $_->{BibliographicItemIdentifier};
2605 $idtype = $_->{BibliographicItemIdentifierCode};
2606 $idfield = 'BibliographicItemIdentifier';
2608 $idvalue = $_->{BibliographicRecordIdentifier};
2609 $idtype = $_->{BibliographicRecordIdentifierCode};
2610 $idfield = 'BibliographicRecordIdentifier';
2612 $item = $self->_bib_search($idvalue, $idtype);
2613 if (ref($item) eq 'NCIP::Problem') {
2614 $stashed_problem = $item unless($stashed_problem);
2615 $stashed_problem->ProblemElement($idfield);
2620 $item = $stashed_problem if (!$item && $stashed_problem);
2626 # private subroutines not meant to be used directly by subclasses.
2627 # Most have to do with setup and/or state checking of implementation
2630 # Find, load, and parse our configuration file:
2634 # Find the configuration file via variables:
2635 my $file = OILS_NCIP_CONFIG_DEFAULT;
2636 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2638 $self->{config} = XMLin($file, NormaliseSpace => 2,
2639 ForceArray => ['block_profile', 'stat_cat_entry']);
2642 # Bootstrap OpenSRF::System and load the IDL.
2646 my $bootstrap_config = $self->{config}->{bootstrap};
2647 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2649 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2650 Fieldmapper->import(IDL => $idl);
2653 # Login and then initialize some object data based on the
2658 # Login to Evergreen.
2661 # Load the barred groups as pgt objects into a blocked_profiles
2663 $self->{blocked_profiles} = [];
2664 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2667 $pgt = $U->simplereq(
2669 'open-ils.pcrud.retrieve.pgt',
2670 $self->{session}->{authtoken},
2674 $pgt = $U->simplereq(
2676 'open-ils.pcrud.search.pgt',
2677 $self->{session}->{authtoken},
2681 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2684 # Load the bib source if we're not using precats.
2685 unless ($self->{config}->{items}->{use_precats}) {
2686 # Retrieve the default
2687 $self->{bib_source} = $U->simplereq(
2689 'open-ils.pcrud.retrieve.cbs',
2690 $self->{session}->{authtoken},
2691 BIB_SOURCE_DEFAULT);
2692 my $data = $self->{config}->{items}->{bib_source};
2694 $data = $data->[0] if (ref($data) eq 'ARRAY');
2697 $result = $U->simplereq(
2699 'open-ils.pcrud.retrieve.cbs',
2700 $self->{session}->{authtoken},
2704 $result = $U->simplereq(
2706 'open-ils.pcrud.search.cbs',
2707 $self->{session}->{authtoken},
2711 $self->{bib_source} = $result if ($result);
2715 # Load the required asset.stat_cat_entries:
2716 $self->{stat_cat_entries} = [];
2717 # First, make a regex for our ou and ancestors:
2718 my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2719 my $re = qr/(?:$ancestors)/;
2720 # Get the uniq stat_cat ids from the configuration:
2721 my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2722 # Retrieve all of the fleshed stat_cats and entries for the above.
2723 my $stat_cats = $U->simplereq(
2725 'open-ils.circ.stat_cat.asset.retrieve.batch',
2726 $self->{session}->{authtoken},
2729 foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2730 # Must have the stat_cat attr and the name, so we must have a
2732 next unless(ref $entry);
2733 my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2734 push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2738 # Search asset.call_number by a bre.id and location object. Return the
2739 # "closest" call_number if found, undef otherwise.
2740 sub _call_number_search {
2743 my $location = shift;
2745 # At some point, this should be smarter, and we should retrieve
2746 # ancestors and descendants and search with a JSON query or some
2747 # such with results ordered by proximity to the original location,
2748 # but I don't have time to implement that right now.
2749 my $acn = $U->simplereq(
2751 'open-ils.pcrud.search.acn',
2752 $self->{session}->{authtoken},
2753 {record => $bibid, owning_lib => $location->id()}
2759 # Do a multiclass.query to search for items by isbn or issn.
2762 my $idvalue = shift;
2766 my $result = $U->simplereq(
2768 'open-ils.search.biblio.multiclass',
2769 {searches => {lc($idtype) => $idvalue}}
2772 if ($result && $result->{count}) {
2773 if ($result->{count} > 1) {
2774 $item = NCIP::Problem->new(
2776 ProblemType => 'Non-Unique Item',
2777 ProblemDetail => 'More than one item matches the request.',
2778 ProblemElement => '',
2779 ProblemValue => $idvalue
2783 my $bibid = $result->{ids}->[0]->[0];
2784 $item = $U->simplereq(
2786 'open-ils.pcrud.retrieve.bre',
2787 $self->{session}->{authtoken},
2795 # Search for holds using the user and copy_details information:
2799 my $copy_details = shift;
2803 # Retrieve all of the user's active holds, and then search them in Perl.
2804 my $holds_list = $U->simplereq(
2806 'open-ils.circ.holds.retrieve',
2807 $self->{session}->{authtoken},
2812 if ($holds_list && @$holds_list) {
2814 # Look for title holds (the most common), first:
2815 my $targetid = $copy_details->{mvr}->doc_id();
2816 @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2818 # Look for volume holds, the next most common:
2819 $targetid = $copy_details->{volume}->id();
2820 @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2823 # Look for copy and force holds, the least likely.
2824 $targetid = $copy_details->{copy}->id();
2825 @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
2827 # There should only be 1, at this point, if there are any.
2836 # Standalone, "helper" functions. These do not take an object or
2839 # Check if a user is past their expiration date.
2844 # Users might not expire. If so, they have no expire_date.
2845 if ($user->expire_date()) {
2846 my $expires = DateTime::Format::ISO8601->parse_datetime(
2847 cleanse_ISO8601($user->expire_date())
2849 my $now = DateTime->now()->epoch();
2850 $expired = $now > $expires;
2856 # Creates a NCIP Problem from an event. Takes a string for the problem
2857 # type, the event hashref (or a string to use for the detail), and
2858 # optional arguments for the ProblemElement and ProblemValue fields.
2859 sub _problem_from_event {
2860 my ($type, $evt, $element, $value) = @_;
2866 my ($textcode, $desc);
2868 # Get the textcode, if available. Otherwise, use the ilsevent
2869 # "id," if available.
2870 if ($evt->{textcode}) {
2871 $textcode = $evt->{textcode};
2872 } elsif ($evt->{ilsevent}) {
2873 $textcode = $evt->{ilsevent};
2876 # Get the description. We favor translated descriptions over
2877 # the English in ils_events.xml.
2879 $desc = $evt->{desc};
2882 # Check if $type was set. As an "undocumented" feature, you
2883 # can pass undef, and we'll use the textcode from the event.
2890 # Set the detail from some combination of the above.
2893 } elsif ($textcode eq 'PERM_FAILURE') {
2894 if ($evt->{ilsperm}) {
2895 $detail = "Permission denied: " . $evt->{ilsperm};
2896 $detail =~ s/\.override$//;
2898 } elsif ($textcode) {
2899 $detail = "ILS returned $textcode error.";
2901 $detail = 'Detail not available.';
2908 return NCIP::Problem->new(
2910 ProblemType => ($type) ? $type : 'Temporary Processing Failure',
2911 ProblemDetail => ($detail) ? $detail : 'Detail not available.',
2912 ProblemElement => ($element) ? $element : 'NULL',
2913 ProblemValue => ($value) ? $value : 'NULL'