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 UserIdentifierValue => $user->card->barcode() || $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 # Add a "dummy" call_number if call_number is not set to something usable.
277 if (!$item_info->{call_number} || (ref($item_info->{call_number}) eq 'HASH' && !%{$item_info->{call_number}})) {
278 # We'll concatenate the FromAgenyId and the RequestId, and
279 # if that doesn't work, use the barcode.
280 my $from_agy = $request->{$message}->{InitiationHeader}->{FromAgencyId}->{AgencyId};
281 my $request_id = $request->{$message}->{RequestId}->{RequestIdentifierValue};
282 # Being a little overcautious here.
283 if ($from_agy && !ref($from_agy)) {
284 $from_agy =~ s/^.*://;
289 if ($from_agy && $request_id && !ref($request_id)) {
290 $item_info->{call_number} = $from_agy . " " . $request_id;
292 $item_info->{call_number} = $item_info->{barcode};
296 if ($self->{config}->{items}->{use_precats}) {
297 # We only need to create a precat copy.
298 $item = $self->create_precat_copy($item_info);
300 # We have to create a "partial" bib record, a call number, and a copy.
301 $item = $self->create_fuller_copy($item_info);
304 # If we failed to create the copy, report a problem.
308 ProblemType => 'Temporary Processing Failure',
309 ProblemDetail => 'Failed to create the item in the system',
310 ProblemElement => $item_idfield,
311 ProblemValue => $item_barcode
317 # We try to find the pickup location in our database. It's OK
318 # if it does not exist, the user's home library will be used
320 my $location = $self->find_location_failover($request->{$message}->{PickupLocation}, $request, $message);
322 # Now, we place the hold on the newly created copy on behalf
323 # of the patron retrieved above.
324 my $hold = $self->place_hold($item, $user, $location, undef, undef, 1);
325 if (ref($hold) eq 'NCIP::Problem') {
326 $response->problem($hold);
330 # Add a hold note with the RequestIdentifierValue for later
331 # lookup in CancelRequestItem. We do not care if it fails.
332 $self->create_hold_note($hold, 'NCIP Remote Request ID', $request->{$message}->{RequestId}->{RequestIdentifierValue});
334 # We return the RequestId and optionally, the ItemID. We'll
335 # just return what was sent to us, since we ignored all of it
338 $data->{RequestId} = NCIP::RequestId->new(
340 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
341 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
342 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
345 $data->{ItemId} = NCIP::Item::Id->new(
347 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
348 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
349 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
352 $response->data($data);
355 my $problem = NCIP::Problem->new();
356 $problem->ProblemType('Unauthorized Combination Of Element Values For System');
357 $problem->ProblemDetail('We only support Hold For Pickup');
358 $problem->ProblemElement('RequestedActionType');
359 $problem->ProblemValue($request->{$message}->{RequestedActionType});
360 $response->problem($problem);
368 $response = $ils->checkinitem($request);
370 Checks the item in if we can find the barcode in the message. It
371 returns problems if it cannot find the item in the system or if the
372 item is not checked out.
374 It could definitely use some more brains at some point as it does not
375 fully support everything that the standard allows. It also does not
376 really check if the checkin succeeded or not.
384 # Check our session and login if necessary:
385 $self->login() unless ($self->checkauth());
388 my $message = $self->parse_request_type($request);
389 my $response = NCIP::Response->new({type => $message . 'Response'});
390 $response->header($self->make_header($request));
392 # We need the copy barcode from the message.
393 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
394 if (ref($item_barcode) eq 'NCIP::Problem') {
395 $response->problem($item_barcode);
399 # Retrieve the copy details.
400 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
402 # Return an Unknown Item problem unless we find the copy.
406 ProblemType => 'Unknown Item',
407 ProblemDetail => "Item with barcode $item_barcode is not known.",
408 ProblemElement => $item_idfield,
409 ProblemValue => $item_barcode
416 # Check if a UserId was provided. If so, this is the patron to
417 # whom the copy should be checked out.
419 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
420 # We ignore the problem, because the UserId is optional.
421 if (ref($user_barcode) ne 'NCIP::Problem') {
422 $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
423 # We don't ignore a problem here, however.
424 if (ref($user) eq 'NCIP::Problem') {
425 $response->problem($user);
431 my $copy = $details->{copy};
433 # Look for a circulation or hold so we can retrieve the user.
434 my $circ = $details->{circ} || $details->{hold};
436 # Check the circ details to see if the copy is checked out and, if
437 # the patron was provided, that it is checked out to the patron in
438 # question. We also verify the copy ownership and circulation
440 my $problem = $self->check_circ_details($details, $user);
442 # We need to fill in some information, however.
443 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
444 $problem->ProblemValue($user_barcode);
445 $problem->ProblemElement($user_idfield);
446 } elsif (!$problem->ProblemElement()) {
447 $problem->ProblemElement($item_idfield);
449 $response->problem($problem);
453 # Checkin parameters. We want to skip hold targeting or making
454 # transits, to force the checkin despite the copy status, as
455 # well as void overdues.
457 copy_barcode => $copy->barcode(),
463 my $result = $U->simplereq(
465 'open-ils.circ.checkin.override',
466 $self->{session}->{authtoken},
469 if (ref($result) eq 'ARRAY') {
470 $result = $result->[0];
472 if ($result->{textcode} eq 'SUCCESS') {
473 # We need to retrieve the copy again because its status may
474 # have changed, and it could have been in a state that won't
475 # let us delete it before the checkin.
476 $details = $self->retrieve_copy_details_by_barcode($copy->barcode());
477 $copy = $details->{copy};
479 # Delete the copy. Since delete_copy checks ownership
480 # before attempting to delete the copy, we don't bother
481 # checking who owns it.
482 $self->delete_copy($copy);
483 # We need the circulation user for the information below, so we retrieve it.
484 my $circ_user = $self->retrieve_user_by_id($circ->usr());
486 ItemId => NCIP::Item::Id->new(
488 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
489 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
490 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
493 UserId => NCIP::User::Id->new(
495 UserIdentifierType => 'Barcode Id',
496 UserIdentifierValue => $circ_user->card->barcode()
501 # Look for UserElements requested and add it to the response:
502 my $elements = $request->{$message}->{UserElementType};
504 $elements = [$elements] unless (ref $elements eq 'ARRAY');
505 my $optionalfields = $self->handle_user_elements($circ_user, $elements);
506 $data->{UserOptionalFields} = $optionalfields;
508 $elements = $request->{$message}->{ItemElementType};
510 $elements = [$elements] unless (ref $elements eq 'ARRAY');
511 my $optionalfields = $self->handle_item_elements($copy, $elements);
512 $data->{ItemOptionalFields} = $optionalfields;
515 $response->data($data);
517 # At some point in the future, we should probably check if
518 # they requested optional user or item elements and return
519 # those. For the time being, we ignore those at the risk of
520 # being considered non-compliant.
522 $response->problem(_problem_from_event('Checkin Failed', $result));
530 $response = $ils->renewitem($request);
532 Handle the RenewItem message.
540 # Check our session and login if necessary:
541 $self->login() unless ($self->checkauth());
544 my $message = $self->parse_request_type($request);
545 my $response = NCIP::Response->new({type => $message . 'Response'});
546 $response->header($self->make_header($request));
548 # We need the copy barcode from the message.
549 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
550 if (ref($item_barcode) eq 'NCIP::Problem') {
551 $response->problem($item_barcode);
555 # Retrieve the copy details.
556 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
558 # Return an Unknown Item problem unless we find the copy.
562 ProblemType => 'Unknown Item',
563 ProblemDetail => "Item with barcode $item_barcode is not known.",
564 ProblemElement => $item_idfield,
565 ProblemValue => $item_barcode
572 # User is required for RenewItem.
573 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
574 if (ref($user_barcode) eq 'NCIP::Problem') {
575 $response->problem($user_barcode);
578 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
579 if (ref($user) eq 'NCIP::Problem') {
580 $response->problem($user);
585 my $copy = $details->{copy};
587 # Look for a circulation and examine its information:
588 my $circ = $details->{circ};
590 # Check the circ details to see if the copy is checked out and, if
591 # the patron was provided, that it is checked out to the patron in
592 # question. We also verify the copy ownership and circulation
594 my $problem = $self->check_circ_details($details, $user, 1);
596 # We need to fill in some information, however.
597 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
598 $problem->ProblemValue($user_barcode);
599 $problem->ProblemElement($user_idfield);
600 } elsif (!$problem->ProblemElement()) {
601 $problem->ProblemElement($item_idfield);
603 $response->problem($problem);
607 # Check if user is blocked from renewals:
608 $problem = $self->check_user_for_problems($user, 'RENEW');
610 # Replace the ProblemElement and ProblemValue fields.
611 $problem->ProblemElement($user_idfield);
612 $problem->ProblemValue($user_barcode);
613 $response->problem($problem);
617 # Check if the duration rule allows renewals. It should have been
618 # fleshed during the copy details retrieve.
619 my $rule = $circ->duration_rule();
620 unless (ref($rule)) {
621 $rule = $U->simplereq(
623 'open-ils.pcrud.retrieve.crcd',
624 $self->{session}->{authtoken},
628 if ($rule->max_renewals() < 1) {
632 ProblemType => 'Item Not Renewable',
633 ProblemDetail => 'Item may not be renewed.',
634 ProblemElement => $item_idfield,
635 ProblemValue => $item_barcode
642 # Check if there are renewals remaining on the latest circ:
643 if ($circ->renewal_remaining() < 1) {
647 ProblemType => 'Maximum Renewals Exceeded',
648 ProblemDetail => 'Renewal cannot proceed because the User has already renewed the Item the maximum number of times permitted.',
649 ProblemElement => $item_idfield,
650 ProblemValue => $item_barcode
657 # Now, we attempt the renewal. If it fails, we simply say that the
658 # user is not allowed to renew this item, without getting into
661 copy_id => $copy->id(),
662 patron_id => $user->id(),
665 my $r = $U->simplereq(
667 'open-ils.circ.renew.override',
668 $self->{session}->{authtoken},
672 # We only look at the first one, since more than one usually means
674 if (ref($r) eq 'ARRAY') {
677 if ($r->{textcode} ne 'SUCCESS') {
678 $problem = _problem_from_event('Renewal Failed', $r);
679 $response->problem($problem);
682 ItemId => NCIP::Item::Id->new(
684 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
685 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
686 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
689 UserId => NCIP::User::Id->new(
691 UserIdentifierType => 'Barcode Id',
692 UserIdentifierValue => $user->card->barcode()
696 # We need to retrieve the copy details again to refresh our
697 # circ information to get the new due date.
698 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
699 $circ = $details->{circ};
700 $data->{DateDue} = _fix_date($circ->due_date());
702 # Look for UserElements requested and add it to the response:
703 my $elements = $request->{$message}->{UserElementType};
705 $elements = [$elements] unless (ref $elements eq 'ARRAY');
706 my $optionalfields = $self->handle_user_elements($user, $elements);
707 $data->{UserOptionalFields} = $optionalfields;
709 $elements = $request->{$message}->{ItemElementType};
711 $elements = [$elements] unless (ref $elements eq 'ARRAY');
712 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
713 $data->{ItemOptionalFields} = $optionalfields;
716 $response->data($data);
719 # At some point in the future, we should probably check if
720 # they requested optional user or item elements and return
721 # those. For the time being, we ignore those at the risk of
722 # being considered non-compliant.
729 $response = $ils->checkoutitem($request);
731 Handle the Checkoutitem message.
739 # Check our session and login if necessary:
740 $self->login() unless ($self->checkauth());
743 my $message = $self->parse_request_type($request);
744 my $response = NCIP::Response->new({type => $message . 'Response'});
745 $response->header($self->make_header($request));
747 # We need the copy barcode from the message.
748 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
749 if (ref($item_barcode) eq 'NCIP::Problem') {
750 $response->problem($item_barcode);
754 # Retrieve the copy details.
755 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
757 # Return an Unknown Item problem unless we find the copy.
761 ProblemType => 'Unknown Item',
762 ProblemDetail => "Item with barcode $item_barcode is not known.",
763 ProblemElement => $item_idfield,
764 ProblemValue => $item_barcode
771 # User is required for CheckOutItem.
772 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
773 if (ref($user_barcode) eq 'NCIP::Problem') {
774 $response->problem($user_barcode);
777 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
778 if (ref($user) eq 'NCIP::Problem') {
779 $response->problem($user);
784 my $copy = $details->{copy};
786 # Check if the copy can circulate.
787 unless ($self->copy_can_circulate($copy)) {
791 ProblemType => 'Item Does Not Circulate',
792 ProblemDetail => "Item with barcode $item_barcode does not circulate.",
793 ProblemElement => $item_idfield,
794 ProblemValue => $item_barcode
801 # Look for a circulation and examine its information:
802 my $circ = $details->{circ};
804 # Check if the item is already checked out.
805 if ($circ && !$circ->checkin_time()) {
809 ProblemType => 'Item Already Checked Out',
810 ProblemDetail => "Item with barcode $item_barcode is already checked out.",
811 ProblemElement => $item_idfield,
812 ProblemValue => $item_barcode
819 # Check if user is blocked from circulation:
820 my $problem = $self->check_user_for_problems($user, 'CIRC');
822 # Replace the ProblemElement and ProblemValue fields.
823 $problem->ProblemElement($user_idfield);
824 $problem->ProblemValue($user_barcode);
825 $response->problem($problem);
829 # Check for the copy being in transit and receive or abort it.
830 my $transit = $U->simplereq(
832 'open-ils.circ.open_copy_transit.retrieve',
833 $self->{session}->{authtoken},
836 if (ref($transit) eq 'Fieldmapper::action::transit_copy') {
837 if ($transit->dest() == $self->{session}->{work_ou}->id()) {
838 my $r = $U->simplereq(
840 'open-ils.circ.copy_transit.receive',
841 $self->{session}->{authtoken},
842 {copyid => $copy->id()}
844 } elsif ($transit->source() == $self->{session}->{work_ou}->id()) {
845 my $r = $U->simplereq(
847 'open-ils.circ.transit.abort',
848 $self->{session}->{authtoken},
849 {copyid => $copy->id()}
854 # Now, we attempt the check out. If it fails, we simply say that
855 # the user is not allowed to check out this item, without getting
858 copy_id => $copy->id(),
859 patron_id => $user->id(),
861 my $r = $U->simplereq(
863 'open-ils.circ.checkout.full.override',
864 $self->{session}->{authtoken},
868 # We only look at the first one, since more than one usually means
870 if (ref($r) eq 'ARRAY') {
873 if ($r->{textcode} ne 'SUCCESS') {
874 $problem = _problem_from_event('Check Out Failed', $r);
875 $response->problem($problem);
878 ItemId => NCIP::Item::Id->new(
880 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
881 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
882 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
885 UserId => NCIP::User::Id->new(
887 UserIdentifierType => 'Barcode Id',
888 UserIdentifierValue => $user->card->barcode()
892 # We need to retrieve the copy details again to refresh our
893 # circ information to get the due date.
894 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
895 $circ = $details->{circ};
896 $data->{DateDue} = _fix_date($circ->due_date());
898 # Look for UserElements requested and add it to the response:
899 my $elements = $request->{$message}->{UserElementType};
901 $elements = [$elements] unless (ref $elements eq 'ARRAY');
902 my $optionalfields = $self->handle_user_elements($user, $elements);
903 $data->{UserOptionalFields} = $optionalfields;
905 $elements = $request->{$message}->{ItemElementType};
907 $elements = [$elements] unless (ref $elements eq 'ARRAY');
908 my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
909 $data->{ItemOptionalFields} = $optionalfields;
912 $response->data($data);
915 # At some point in the future, we should probably check if
916 # they requested optional user or item elements and return
917 # those. For the time being, we ignore those at the risk of
918 # being considered non-compliant.
925 $response = $ils->requestitem($request);
927 Handle the NCIP RequestItem message.
934 # Check our session and login if necessary:
935 $self->login() unless ($self->checkauth());
938 my $message = $self->parse_request_type($request);
939 my $response = NCIP::Response->new({type => $message . 'Response'});
940 $response->header($self->make_header($request));
942 # Because we need to have a user to place a hold, because the user
943 # is likely to have problems, and because getting the item
944 # information for the hold is trickier than getting the user
945 # information, we'll do the user first and short circuit out of
946 # the function if there is a problem with the user.
947 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
948 if (ref($user_barcode) eq 'NCIP::Problem') {
949 $response->problem($user_barcode);
952 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
953 if (ref($user) eq 'NCIP::Problem') {
954 $response->problem($user);
957 my $problem = $self->check_user_for_problems($user, 'HOLD');
959 $response->problem($problem);
963 # Auto-Graphics send a single BibliographicRecordId to identify
964 # the "item" to place on hold.
966 if ($request->{$message}->{BibliographicId}) {
967 my $idxml = $request->{$message}->{BibliographicId};
968 # The standard allows more than 1. If that hapens, we only
970 $idxml = $idxml->[0] if (ref($idxml) eq 'ARRAY');
971 if ($idxml->{BibliographicRecordId}) {
972 $bibid = NCIP::Item::BibliographicRecordId->new(
973 $idxml->{BibliographicRecordId}
977 unless ($bibid && $bibid->{BibliographicRecordIdentifier}) {
978 $problem = NCIP::Problem->new(
980 ProblemType => 'Needed Data Missing',
981 ProblemDetail => 'Need BibliographicRecordIdentifier to place request',
982 ProblemElement => 'BibliographicRecordIdentifier',
983 ProblemValue => 'NULL'
986 $response->problem($problem);
990 # We need an actual bre.
991 my $bre = $self->retrieve_biblio_record_entry($bibid->{BibliographicRecordIdentifier});
992 if (!$bre || $U->is_true($bre->deleted())) {
993 $problem = NCIP::Problem->new(
995 ProblemType => 'Unknown Item',
996 ProblemDetail => 'Item ' . $bibid->{BibliographicRecordIdentifier} . ' is unknown',
997 ProblemElement => 'BibliographicRecordIdentifier',
998 ProblemValue => $bibid->{BibliographicRecordIdentifier}
1001 $response->problem($problem);
1005 # Auto-Graphics expects us to limit the selection ou for the hold
1006 # to a given library. We look fo that in the AgencyId of the
1007 # BibliographRecordId or in the ToAgencyId of the main message.
1008 my $selection_ou = $self->find_location_failover($bibid->{AgencyId}, $request, $message);
1009 unless ($selection_ou) {
1010 $problem = NCIP::Problem->new(
1012 ProblemType => 'Unknown Agency',
1013 ProblemDetail => 'Agency is not known',
1014 ProblemElement => 'BibliographicRecordIdentifier',
1015 ProblemValue => $bibid->{AgencyId} || $request->{$message}->{InitiationHeader}->{ToAgencyId}->{AgencyId}
1018 $response->problem($problem);
1022 # See if we were given a pickup location.
1024 if ($request->{$message}->{PickupLocation}) {
1025 my $loc = $request->{$message}->{PickupLocation};
1027 $pickup_ou = $self->retrieve_org_unit_by_shortname($loc);
1030 # Look for a NeedBeforeDate to set the expiration.
1031 my $expiration = $request->{$message}->{NeedBeforeDate};
1033 # Check for eligible copies:
1034 if ($self->count_eligible_copies($bre, $user, $pickup_ou, $selection_ou) == 0) {
1038 ProblemType => 'Item Not Available By Need Before Date',
1039 ProblemDetail => 'Item requested will not be available by the date/time the User needs the Item',
1040 ProblemElement => 'BibliographicRecordIdentifier',
1041 ProblemValue => $bre->id()
1049 my $hold = $self->place_hold($bre, $user, $pickup_ou, $expiration, $selection_ou);
1050 if (ref($hold) eq 'NCIP::Problem') {
1051 $response->problem($hold);
1053 # Add a hold note with the RequestIdentifierValue for later
1054 # lookup in CancelRequestItem. We do not care if it fails.
1055 $self->create_hold_note($hold, 'NCIP Remote Request ID', $request->{$message}->{RequestId}->{RequestIdentifierValue});
1057 RequestId => NCIP::RequestId->new(
1058 $request->{$message}->{RequestId}
1060 ItemId => NCIP::Item::Id->new(
1062 AgencyId => $selection_ou->shortname(),
1063 ItemIdentifierValue => $bre->id(),
1064 ItemIdentifierType => 'SYSNUMBER'
1067 UserId => NCIP::User::Id->new(
1069 UserIdentifierValue => $user->card->barcode(),
1070 UserIdentifierType => 'Barcode Id'
1073 RequestType => $request->{$message}->{RequestType},
1074 RequestScopeType => $request->{$message}->{RequestScopeType},
1077 # Look for UserElements requested and add it to the response:
1078 my $elements = $request->{$message}->{UserElementType};
1080 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1081 my $optionalfields = $self->handle_user_elements($user, $elements);
1082 $data->{UserOptionalFields} = $optionalfields;
1084 $elements = $request->{$message}->{ItemElementType};
1085 if ($elements && $hold->current_copy()) {
1086 my $copy_details = $self->retrieve_copy_details_by_id($hold->current_copy());
1087 $elements = [$elements] unless (ref($elements) eq 'ARRAY');
1088 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1089 $data->{ItemOptionalFields} = $optionalfields;
1092 $response->data($data);
1098 =head2 cancelrequestitem
1100 $response = $ils->cancelrequestitem($request);
1102 Handle the NCIP CancelRequestItem message.
1106 sub cancelrequestitem {
1108 my $request = shift;
1109 # Check our session and login if necessary:
1110 $self->login() unless ($self->checkauth());
1113 my $message = $self->parse_request_type($request);
1114 my $response = NCIP::Response->new({type => $message . 'Response'});
1115 $response->header($self->make_header($request));
1117 # UserId is required by the standard, but we might not really need it.
1118 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1119 if (ref($user_barcode) eq 'NCIP::Problem') {
1120 $response->problem($user_barcode);
1123 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1124 if (ref($user) eq 'NCIP::Problem') {
1125 $response->problem($user);
1129 # First, let's see if we can find the hold via the RequestId's
1130 # RequestIdentifierValue. If not, we fall back on the ItemId.
1131 my $hold = $self->find_hold_via_note('NCIP Remote Request ID', $request->{$message}->{RequestId}->{RequestIdentifierValue});
1134 my $item_id = $request->{$message}->{ItemId};
1136 my $idvalue = $item_id->{ItemIdentifierValue};
1137 my $itemagy = $item_id->{AgencyId};
1138 my $selection_ou = $self->find_location_failover($itemagy, $request, $message);
1139 unless ($selection_ou) {
1140 my $problem = NCIP::Problem->new(
1142 ProblemType => 'Unknown Agency',
1143 ProblemDetail => 'Agency is not known',
1144 ProblemElement => 'AgencyId',
1145 ProblemValue => $item_id->{AgencyId} || $request->{$message}->{InitiationHeader}->{ToAgencyId}->{AgencyId}
1148 $response->problem($problem);
1152 # We should support looking up holds by barcode, since we still
1153 # support placing them by barcode, but that is not how it is going
1154 # to work with Auto-Graphics, apparently. I'll leave the
1155 # reimplementation of that for a future enhancement.
1157 # See if we can find the hold:
1158 my $hold = $self->_hold_search($user, $idvalue, $selection_ou);
1163 # If there is a transit, abort it. NOTE: We do this before
1164 # canceling to avoid negative consequences of retargeting and
1165 # in case the reset of the hold done by the transit abort ever
1166 # messes with cancel_time, etc.
1167 if ($hold->transit() && $self->{abort_transit_on_hold_cancel}) {
1168 $self->abort_transit($hold->transit());
1170 my $result = $self->cancel_hold($hold);
1172 $response->problem(_problem_from_event("Temporary Processing Failure", $result));
1175 RequestId => NCIP::RequestId->new(
1177 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1178 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1179 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1182 UserId => NCIP::User::Id->new(
1184 UserIdentifierType => 'Barcode Id',
1185 UserIdentifierValue => $user->card->barcode()
1188 ItemId => NCIP::Item::Id->new(
1190 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
1191 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
1192 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
1196 # Look for UserElements requested and add it to the response:
1197 my $elements = $request->{$message}->{UserElementType};
1199 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1200 my $optionalfields = $self->handle_user_elements($user, $elements);
1201 $data->{UserOptionalFields} = $optionalfields;
1203 $elements = $request->{$message}->{ItemElementType};
1204 if ($elements && $hold->current_copy()) {
1205 $elements = [$elements] unless (ref $elements eq 'ARRAY');
1206 my $copy_details = $self->retrieve_copy_details_by_id($hold->current_copy());
1207 if ($copy_details) {
1208 my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1209 $data->{ItemOptionalFields} = $optionalfields;
1212 $response->data($data);
1218 ProblemType => 'Unknown Request',
1219 ProblemDetail => 'No request found for the item and user',
1220 ProblemElement => 'NULL',
1221 ProblemValue => 'NULL'
1230 =head1 METHODS USEFUL to SUBCLASSES
1232 =head2 handle_user_elements
1233 $useroptionalfield = $ils->handle_user_elements($user, $elements);
1235 Returns NCIP::User::OptionalFields for the given user and arrayref of
1240 sub handle_user_elements {
1243 my $elements = shift;
1244 my $optionalfields = NCIP::User::OptionalFields->new();
1246 # First, we'll look for name information.
1247 if (grep {$_ eq 'Name Information'} @$elements) {
1248 my $name = NCIP::StructuredPersonalUserName->new();
1249 $name->Surname($user->family_name());
1250 $name->GivenName($user->first_given_name());
1251 $name->Prefix($user->prefix());
1252 $name->Suffix($user->suffix());
1253 $optionalfields->NameInformation($name);
1256 # Next, check for user address information.
1257 if (grep {$_ eq 'User Address Information'} @$elements) {
1260 # See if the user has any valid, physcial addresses.
1261 foreach my $addr (@{$user->addresses()}) {
1262 next if ($U->is_true($addr->pending()));
1263 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
1264 my $structured = NCIP::StructuredAddress->new();
1265 $structured->Line1($addr->street1());
1266 $structured->Line2($addr->street2());
1267 $structured->Locality($addr->city());
1268 $structured->Region($addr->state());
1269 $structured->PostalCode($addr->post_code());
1270 $structured->Country($addr->country());
1271 $address->PhysicalAddress(
1272 NCIP::PhysicalAddress->new(
1274 StructuredAddress => $structured,
1275 Type => 'Postal Address'
1279 push @$addresses, $address;
1282 # Right now, we're only sharing email address if the user
1284 if ($user->email()) {
1285 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
1286 $address->ElectronicAddress(
1287 NCIP::ElectronicAddress->new({
1289 Data=>$user->email()
1292 push @$addresses, $address;
1294 # Auto-graphics asked for the phone numbers.
1295 if ($user->day_phone()) {
1296 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Day Phone'});
1297 $address->ElectronicAddress(
1298 NCIP::ElectronicAddress->new(
1301 Data=>$user->day_phone()
1305 push @$addresses, $address;
1307 if ($user->evening_phone()) {
1308 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Evening Phone'});
1309 $address->ElectronicAddress(
1310 NCIP::ElectronicAddress->new(
1312 Type=>'Evening Phone',
1313 Data=>$user->evening_phone()
1317 push @$addresses, $address;
1319 if ($user->other_phone()) {
1320 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Other Phone'});
1321 $address->ElectronicAddress(
1322 NCIP::ElectronicAddress->new(
1324 Type=>'Other Phone',
1325 Data=>$user->other_phone()
1329 push @$addresses, $address;
1332 $optionalfields->UserAddressInformation($addresses);
1335 # Check for User Privilege.
1336 if (grep {$_ eq 'User Privilege'} @$elements) {
1337 # Get the user's group:
1338 my $pgt = $U->simplereq(
1340 'open-ils.pcrud.retrieve.pgt',
1341 $self->{session}->{authtoken},
1345 my $privilege = NCIP::User::Privilege->new();
1346 $privilege->AgencyId($user->home_ou->shortname());
1347 $privilege->AgencyUserPrivilegeType($pgt->name());
1348 $privilege->ValidToDate(_fix_date($user->expire_date()));
1349 $privilege->ValidFromDate(_fix_date($user->create_date()));
1351 my $status = 'Active';
1352 if (_expired($user)) {
1353 $status = 'Expired';
1354 } elsif ($U->is_true($user->barred())) {
1356 } elsif (!$U->is_true($user->active())) {
1357 $status = 'Inactive';
1360 $privilege->UserPrivilegeStatus(
1361 NCIP::User::PrivilegeStatus->new({
1362 UserPrivilegeStatusType => $status
1367 $optionalfields->UserPrivilege([$privilege]);
1371 # Check for Block Or Trap.
1372 if (grep {$_ eq 'Block Or Trap'} @$elements) {
1375 # First, let's check if the profile is blocked from ILL.
1376 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1377 my $block = NCIP::User::BlockOrTrap->new();
1378 $block->AgencyId($user->home_ou->shortname());
1379 $block->BlockOrTrapType('Block Interlibrary Loan');
1380 push @$blocks, $block;
1383 # Next, we loop through the user's standing penalties
1384 # looking for blocks on CIRC, HOLD, and RENEW.
1385 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
1386 foreach my $penalty (@{$user->standing_penalties()}) {
1387 next unless($penalty->standing_penalty->block_list());
1388 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
1389 my $ou = $U->simplereq(
1391 'open-ils.pcrud.retrieve.aou',
1392 $self->{session}->{authtoken},
1393 $penalty->org_unit()
1397 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
1398 my $bot = NCIP::User::BlockOrTrap->new();
1399 $bot->AgencyId($ou->shortname());
1400 $bot->BlockOrTrapType('Block Checkout');
1401 push @$blocks, $bot;
1406 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
1407 my $bot = NCIP::User::BlockOrTrap->new();
1408 $bot->AgencyId($ou->shortname());
1409 $bot->BlockOrTrapType('Block Holds');
1410 push @$blocks, $bot;
1415 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
1416 my $bot = NCIP::User::BlockOrTrap->new();
1417 $bot->AgencyId($ou->shortname());
1418 $bot->BlockOrTrapType('Block Renewals');
1419 push @$blocks, $bot;
1423 # Stop after we report one of each, even if more
1425 last if ($have_circ && $have_renew && $have_hold);
1428 $optionalfields->BlockOrTrap($blocks);
1431 return $optionalfields;
1434 =head2 handle_item_elements
1438 sub handle_item_elements {
1441 my $elements = shift;
1442 my $optionalfields = NCIP::Item::OptionalFields->new();
1444 my $details; # In case we need for more than one.
1446 if (grep {$_ eq 'Bibliographic Description'} @$elements) {
1448 # Check for a precat copy, 'cause it is simple.
1449 if ($copy->dummy_title()) {
1450 $description = NCIP::Item::BibliographicDescription->new();
1451 $description->Title($copy->dummy_title());
1452 $description->Author($copy->dummy_author());
1453 if ($copy->dummy_isbn()) {
1454 $description->BibliographicItemId(
1455 NCIP::Item::BibliographicItemId->new(
1457 BibliographicItemIdentifier => $copy->dummy_isbn(),
1458 BibliographicItemIdentifierCode => 'ISBN'
1464 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1465 $description = NCIP::Item::BibliographicDescription->new();
1466 $description->Title($details->{mvr}->title());
1467 $description->Author($details->{mvr}->author());
1468 $description->BibliographicRecordId(
1469 NCIP::Item::BibliographicRecordId->new(
1471 BibliographicRecordIdentifier => $details->{mvr}->doc_id(),
1472 BibliographicRecordIdentifierCode => 'SYSNUMBER'
1476 if ($details->{mvr}->publisher()) {
1477 $description->Publisher($details->{mvr}->publisher());
1479 if ($details->{mvr}->pubdate()) {
1480 $description->PublicationDate($details->{mvr}->pubdate());
1482 if ($details->{mvr}->edition()) {
1483 $description->Edition($details->{mvr}->edition());
1486 $optionalfields->BibliographicDescription($description) if ($description);
1489 if (grep {$_ eq 'Item Description'} @$elements) {
1490 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1491 # Call Number is the only field we currently return. We also
1492 # do not attempt to retun a prefix and suffix. Someone else
1493 # can deal with that if they want it.
1494 if ($details->{volume}) {
1495 $optionalfields->ItemDescription(
1496 NCIP::Item::Description->new(
1497 {CallNumber => $details->{volume}->label()}
1503 if (grep {$_ eq 'Circulation Status'} @$elements) {
1504 my $status = $copy->status();
1505 $status = $self->retrieve_copy_status($status) unless (ref($status));
1506 $optionalfields->CirculationStatus($status->name()) if ($status);
1509 if (grep {$_ eq 'Date Due'} @$elements) {
1510 $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1511 if ($details->{circ}) {
1512 if (!$details->{circ}->checkin_time()) {
1513 $optionalfields->DateDue(_fix_date($details->{circ}->due_date()));
1518 if (grep {$_ eq 'Item Use Restriction Type'} @$elements) {
1519 $optionalfields->ItemUseRestrictionType('None');
1522 if (grep {$_ eq 'Physical Condition'} @$elements) {
1523 $optionalfields->PhysicalCondition(
1524 NCIP::Item::PhysicalCondition->new(
1525 {PhysicalConditionType => 'Unknown'}
1530 return $optionalfields;
1537 Login to Evergreen via OpenSRF. It uses internal state from the
1538 configuration file to login.
1542 # Login via OpenSRF to Evergreen.
1546 # Get the authentication seed.
1547 my $seed = $U->simplereq(
1549 'open-ils.auth.authenticate.init',
1550 $self->{config}->{credentials}->{username}
1555 my $response = $U->simplereq(
1557 'open-ils.auth.authenticate.complete',
1559 username => $self->{config}->{credentials}->{username},
1560 password => md5_hex(
1561 $seed . md5_hex($self->{config}->{credentials}->{password})
1564 workstation => $self->{config}->{credentials}->{workstation}
1568 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1569 $self->{session}->{authtime} = $response->{payload}->{authtime};
1571 # Set/reset the work_ou and user data in case something changed.
1573 # Retrieve the work_ou as an object.
1574 $self->{session}->{work_ou} = $U->simplereq(
1576 'open-ils.pcrud.search.aou',
1577 $self->{session}->{authtoken},
1578 {shortname => $self->{config}->{credentials}->{work_ou}}
1581 # We need the user information in order to do some things.
1582 $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1590 $valid = $ils->checkauth();
1592 Returns 1 if the object a 'valid' authtoken, 0 if not.
1599 # We use AppUtils to do the heavy lifting.
1600 if (defined($self->{session})) {
1601 if ($U->check_user_session($self->{session}->{authtoken})) {
1608 # If we reach here, we don't have a session, so we are definitely
1613 =head2 retrieve_user_by_barcode
1615 $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1617 Do a fleshed retrieve of a patron by barcode. Return the patron if
1618 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1620 The id field argument is used for the ProblemElement field in the
1621 NCIP::Problem object.
1623 An invalid patron is one where the barcode is not found in the
1624 database, the patron is deleted, or the barcode used to retrieve the
1625 patron is not active. The problem element is also returned if an error
1626 occurs during the retrieval.
1630 sub retrieve_user_by_barcode {
1631 my ($self, $barcode, $idfield) = @_;
1632 my $result = $U->simplereq(
1634 'open-ils.actor.user.fleshed.retrieve_by_barcode',
1635 $self->{session}->{authtoken},
1640 # Check for a failure, or a deleted, inactive, or expired user,
1641 # and if so, return empty userdata.
1642 if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1643 || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1645 my $problem = NCIP::Problem->new();
1646 $problem->ProblemType('Unknown User');
1647 $problem->ProblemDetail("User with barcode $barcode unknown");
1648 $problem->ProblemElement($idfield);
1649 $problem->ProblemValue($barcode);
1656 =head2 retrieve_user_by_id
1658 $user = $ils->retrieve_user_by_id($id);
1660 Similar to C<retrieve_user_by_barcode> but takes the user's database
1661 id rather than barcode. This is useful when you have a circulation or
1662 hold and need to get information about the user's involved in the hold
1665 It returns a fleshed user on success or undef on failure.
1669 sub retrieve_user_by_id {
1670 my ($self, $id) = @_;
1672 # Do a fleshed retrieve of the patron, and flesh the fields that
1673 # we would normally use.
1674 my $result = $U->simplereq(
1676 'open-ils.actor.user.fleshed.retrieve',
1677 $self->{session}->{authtoken},
1679 [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou', 'settings' ]
1681 # Check for an error.
1682 undef($result) if ($result && $U->event_code($result));
1687 =head2 check_user_for_problems
1689 $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1691 This function checks if a user has a blocked profile or any from a
1692 list of provided blocks. If it does, then a NCIP::Problem object is
1693 returned, otherwise an undefined value is returned.
1695 The list of blocks appears as additional arguments after the user. You
1696 can provide any value(s) that might appear in a standing penalty block
1697 lit in Evergreen. The example above checks for HOLD, CIRC, and
1698 RENEW. Any number of such values can be provided. If none are
1699 provided, the function only checks if the patron's profiles appears in
1700 the object's blocked profiles list.
1702 It stops on the first matching block, if any.
1706 sub check_user_for_problems {
1711 # Fill this in if we have a problem, otherwise just return it.
1714 # First, check the user's profile.
1715 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1716 $problem = NCIP::Problem->new(
1718 ProblemType => 'User Blocked',
1719 ProblemDetail => 'User blocked from inter-library loan',
1720 ProblemElement => 'NULL',
1721 ProblemValue => 'NULL'
1726 # Next, check if the patron has one of the indicated blocks.
1728 foreach my $penalty (@{$user->standing_penalties()}) {
1729 if ($penalty->standing_penalty->block_list()) {
1730 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1731 foreach my $block (@blocks) {
1732 if (grep {$_ =~ /$block/} @pblocks) {
1733 $problem = NCIP::Problem->new(
1735 ProblemType => 'User Blocked',
1736 ProblemDetail => 'User blocked from ' .
1737 ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1738 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1739 ProblemElement => 'NULL',
1740 ProblemValue => 'NULL'
1754 =head2 check_circ_details
1756 $problem = $ils->check_circ_details($details, $user, $isrenewal);
1758 Checks if we can checkin or renew a circulation. That is, the
1759 circulation is still open (i.e. the copy is still checked out), if we
1760 either own the copy or are the circulation location, and if the
1761 circulation is for the optional $user argument. The $details argument
1762 is required and comes from the retrieve_copy_details call. $user is
1765 The optional C<$isrenewal> argument must be true when checking for
1766 renewals. This argument set to true bypasses the hold check
1767 (described below) and requires a circulation.
1769 If we are not checking for renewals, this function will also check for
1770 a shelf-expired hold for the copy and patron. If that is found, it is
1771 considered success as well.
1773 Also, if we are not checking for renewals, it will also check for an
1774 open transit return the item to our working organizational unit.
1776 Returns a problem if any of the above conditions fail. Returns undef
1777 if they pass and we can proceed with the checkin or renewal.
1779 If the failure occurred on the copy-related checks, then the
1780 ProblemElement field will be undefined and needs to be filled in with
1781 the item id field name. If the check for the copy being checked out to
1782 the provided user fails, then both ProblemElement and ProblemValue
1783 fields will be empty and need to be filled in by the caller.
1787 sub check_circ_details {
1788 my ($self, $details, $user, $isrenewal) = @_;
1790 my $copy = $details->{copy};
1791 my $circ = $details->{circ};
1792 my $transit = $details->{transit};
1793 my $hold = $details->{hold};
1795 # User from the hold or circulation.
1798 # Shortcut for the next check.
1799 my $ou_id = $self->{session}->{work_ou}->id();
1801 # We need to have a circulation. The copy needs to either have
1802 # been checked out at the NCIP user's working_ou or it needs to be
1803 # owned there. If the circulation was subsequently checked in,
1804 # then we need an open transit to the NCIP user's working_ou.
1806 if (($circ->circ_lib() == $ou_id || $copy->circ_lib() == $ou_id)
1807 || ($circ->checkin_time() && !$isrenewal && ($transit && $transit->dest() == $ou_id))) {
1808 $circ_user = $self->retrieve_user_by_id($circ->usr());
1810 } elsif ($hold && !$isrenewal) {
1811 # If we don't have a circulation, we want to have a shelf-expired hold.
1812 if ($hold->shelf_time() && _date_past($hold->shelf_expire_time())) {
1813 $circ_user = $self->retrieve_user_by_id($hold->usr());
1818 # Check if the $circ_user matches the passed in $user.
1819 if ($user && $circ_user && $user->id() != $circ_user->id()) {
1820 # The ProblemElement and ProblemValue field need to be
1821 # filled in by the caller.
1822 return NCIP::Problem->new(
1824 ProblemType => 'Item Not Checked Out To This User',
1825 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1830 # We consider the item to be not checked out.
1831 return NCIP::Problem->new(
1833 ProblemType => 'Item Not Checked Out',
1834 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1835 ProblemValue => $copy->barcode()
1839 # If we get here, we're good to go.
1843 =head2 retrieve_copy_details_by_barcode
1845 $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1847 Look up and retrieve some copy details by the copy barcode. This
1848 method returns either a hashref with the copy details or undefined if
1849 no copy exists with that barcode or if some error occurs.
1851 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1853 This method differs from C<retrieve_user_by_barcode> in that a copy
1854 cannot be invalid if it exists and it is not always an error if no
1855 copy exists. In some cases, when handling AcceptItem, we might prefer
1856 there to be no copy.
1860 sub retrieve_copy_details_by_barcode {
1862 my $barcode = shift;
1864 my $copy = $U->simplereq(
1866 'open-ils.circ.copy_details.retrieve.barcode',
1867 $self->{session}->{authtoken},
1871 # If $copy is an event, return undefined.
1872 if ($copy && $U->event_code($copy)) {
1879 =head2 retrieve_copy_details_by_id
1881 $copy = $ils->retrieve_copy_details_by_id($copy_id);
1883 Retrieve copy_details by copy id. Same as the above, but with a copy
1884 id instead of barcode.
1888 sub retrieve_copy_details_by_id {
1890 my $copy_id = shift;
1892 my $copy = $U->simplereq(
1894 'open-ils.circ.copy_details.retrieve',
1895 $self->{session}->{authtoken},
1899 # If $copy is an event, return undefined.
1900 if ($copy && $U->event_code($copy)) {
1907 =head2 retrieve_copy_status
1909 $status = $ils->retrieve_copy_status($id);
1911 Retrive a copy status object by database ID.
1915 sub retrieve_copy_status {
1919 my $status = $U->simplereq(
1921 'open-ils.pcrud.retrieve.ccs',
1922 $self->{session}->{authtoken},
1929 =head2 retrieve_org_unit_by_shortname
1931 $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1933 Retrieves an org. unit from the database by shortname, and fleshes the
1934 ou_type field. Returns the org. unit as a Fieldmapper object or
1939 sub retrieve_org_unit_by_shortname {
1941 my $shortname = shift;
1943 my $aou = $U->simplereq(
1945 'open-ils.actor.org_unit.retrieve_by_shortname',
1949 # Check for failure from the above.
1950 if (ref($aou) eq 'HASH') {
1954 # We want to retrieve the type and manually "flesh" the object.
1956 my $type = $U->simplereq(
1958 'open-ils.pcrud.retrieve.aout',
1959 $self->{session}->{authtoken},
1962 $aou->ou_type($type) if ($type);
1968 =head2 retrieve_copy_location
1970 $location = $ils->retrieve_copy_location($location_id);
1972 Retrieve a copy location based on id.
1976 sub retrieve_copy_location {
1980 my $location = $U->simplereq(
1982 'open-ils.pcrud.retrieve.acpl',
1983 $self->{session}->{authtoken},
1990 =head2 retrieve_biblio_record_entry
1992 $bre = $ils->retrieve_biblio_record_entry($bre_id);
1994 Given a biblio.record_entry.id, this method retrieves a bre object.
1998 sub retrieve_biblio_record_entry {
2002 my $bre = $U->simplereq(
2004 'open-ils.pcrud.retrieve.bre',
2005 $self->{session}->{authtoken},
2012 =head2 create_precat_copy
2015 barcode => '312340123456789',
2016 author => 'Public, John Q.',
2017 title => 'Magnum Opus',
2018 call_number => '005.82',
2019 publisher => 'Brick House',
2020 publication_date => '2014'
2023 $item = $ils->create_precat_copy($item_info);
2026 Create a "precat" copy to use for the incoming item using a hashref of
2027 item information. At a minimum, the barcode, author and title fields
2028 need to be filled in. The other fields are ignored if provided.
2030 This method is called by the AcceptItem handler if the C<use_precats>
2031 configuration option is turned on.
2035 sub create_precat_copy {
2037 my $item_info = shift;
2039 my $item = Fieldmapper::asset::copy->new();
2040 $item->barcode($item_info->{barcode});
2041 $item->call_number(OILS_PRECAT_CALL_NUMBER);
2042 $item->dummy_title($item_info->{title});
2043 $item->dummy_author($item_info->{author});
2044 $item->circ_lib($self->{session}->{work_ou}->id());
2045 $item->circulate('t');
2046 $item->holdable('t');
2047 $item->opac_visible('f');
2048 $item->deleted('f');
2049 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2050 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2053 $item->editor($self->{session}->{user}->id());
2054 $item->creator($self->{session}->{user}->id());
2057 # Actually create it:
2059 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2062 $xact = $ses->request(
2063 'open-ils.pcrud.transaction.begin',
2064 $self->{session}->{authtoken}
2066 $item = $ses->request(
2067 'open-ils.pcrud.create.acp',
2068 $self->{session}->{authtoken},
2071 $xact = $ses->request(
2072 'open-ils.pcrud.transaction.commit',
2073 $self->{session}->{authtoken}
2081 'open-ils.pcrud.transaction.rollback',
2082 $self->{session}->{authtoken}
2092 =head2 create_fuller_copy
2095 barcode => '31234003456789',
2096 author => 'Public, John Q.',
2097 title => 'Magnum Opus',
2098 call_number => '005.82',
2099 publisher => 'Brick House',
2100 publication_date => '2014'
2103 $item = $ils->create_fuller_copy($item_info);
2105 Creates a skeletal bibliographic record, call number, and copy for the
2106 incoming item using a hashref with item information in it. At a
2107 minimum, the barcode, author, title, and call_number fields must be
2110 This method is used by the AcceptItem handler if the C<use_precats>
2111 configuration option is NOT set.
2115 sub create_fuller_copy {
2117 my $item_info = shift;
2121 # We do everything in one transaction, because it should be atomic.
2122 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2126 $xact = $ses->request(
2127 'open-ils.pcrud.transaction.begin',
2128 $self->{session}->{authtoken}
2135 # The rest depends on there being a transaction.
2138 # Create the MARC record.
2139 my $record = MARC::Record->new();
2140 $record->encoding('UTF-8');
2141 $record->leader('00881nam a2200193 4500');
2142 my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
2144 push(@fields, MARC::Field->new('005', $datespec));
2145 push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
2146 push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
2147 # Publisher is a little trickier:
2148 if ($item_info->{publisher}) {
2149 my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
2150 $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
2151 push(@fields, $pub);
2153 # We have no idea if the author is personal corporate or something else, so we use a 720.
2154 push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
2155 $record->append_fields(@fields);
2156 my $marc = clean_marc($record);
2158 # Create the bib object.
2159 my $bib = Fieldmapper::biblio::record_entry->new();
2160 $bib->creator($self->{session}->{user}->id());
2161 $bib->editor($self->{session}->{user}->id());
2162 $bib->source($self->{bib_source}->id());
2169 $bib = $ses->request(
2170 'open-ils.pcrud.create.bre',
2171 $self->{session}->{authtoken},
2179 'open-ils.pcrud.transaction.rollback',
2180 $self->{session}->{authtoken}
2185 # Create the call number
2188 $acn = Fieldmapper::asset::call_number->new();
2189 $acn->creator($self->{session}->{user}->id());
2190 $acn->editor($self->{session}->{user}->id());
2191 $acn->label($item_info->{call_number});
2192 $acn->record($bib->id());
2193 $acn->owning_lib($self->{session}->{work_ou}->id());
2198 $acn = $ses->request(
2199 'open-ils.pcrud.create.acn',
2200 $self->{session}->{authtoken},
2208 'open-ils.pcrud.transaction.rollback',
2209 $self->{session}->{authtoken}
2217 $item = Fieldmapper::asset::copy->new();
2218 $item->barcode($item_info->{barcode});
2219 $item->call_number($acn->id());
2220 $item->circ_lib($self->{session}->{work_ou}->id);
2221 $item->circulate('t');
2222 if ($self->{config}->{items}->{use_force_holds}) {
2223 $item->holdable('f');
2225 $item->holdable('t');
2227 $item->opac_visible('f');
2228 $item->deleted('f');
2229 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2230 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2233 $item->editor($self->{session}->{user}->id);
2234 $item->creator($self->{session}->{user}->id);
2238 $item = $ses->request(
2239 'open-ils.pcrud.create.acp',
2240 $self->{session}->{authtoken},
2244 # Cross our fingers and commit the work.
2245 $xact = $ses->request(
2246 'open-ils.pcrud.transaction.commit',
2247 $self->{session}->{authtoken}
2254 'open-ils.pcrud.transaction.rollback',
2255 $self->{session}->{authtoken}
2256 )->gather(1) if ($xact);
2262 # We need to disconnect our session.
2265 # Now, we handle our asset stat_cat entries.
2267 # It would be nice to do these in the above transaction, but
2268 # pcrud does not support the ascecm object, yet.
2269 foreach my $entry (@{$self->{stat_cat_entries}}) {
2270 my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2272 $map->stat_cat($entry->stat_cat());
2273 $map->stat_cat_entry($entry->id());
2274 $map->owning_copy($item->id());
2275 # We don't really worry if it succeeds or not.
2278 'open-ils.circ.stat_cat.asset.copy_map.create',
2279 $self->{session}->{authtoken},
2290 $hold = $ils->place_hold($item, $user, $location, $expiration, $org_unit, $do_notification);
2292 This function places a hold on $item for $user for pickup at
2293 $location. If location is not provided or undefined, the user's home
2294 library is used as a fallback.
2296 The $expiration argument is optional and must be a properly formatted
2297 ISO date time. It will be used as the hold expire time, if
2298 provided. Otherwise the system default time will be used.
2300 The $org_unit parameter is only consulted in the event of $item being
2301 a biblio::record_entry object. In which case, it is expected to be
2302 undefined or an actor::org_unit object. If it is present, then its id
2303 and ou_type depth (if the ou_type field is fleshed) will be used to
2304 control the selection ou and selection depth for the hold. This
2305 essentially limits the hold to being filled by copies belonging to the
2306 specified org_unit or its children.
2308 The $do_notification parameter is true or false for whether or not to
2309 add the patron's default notification options to the hold when placed.
2311 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2312 (biblio::record_entry). The appropriate hold type will be placed
2313 depending on the object.
2315 On success, the method returns the object representing the hold. On
2316 failure, a NCIP::Problem object, describing the failure, is returned.
2324 my $location = shift;
2325 my $expiration = shift;
2326 my $org_unit = shift;
2327 my $do_notification = shift;
2329 # If $location is undefined, use the user's home_ou, which should
2330 # have been fleshed when the user was retrieved.
2331 $location = $user->home_ou() unless ($location);
2333 # $params for the hold.
2334 my $params = { pickup_lib => $location->id(), patronid => $user->id() };
2336 if (ref($item) eq 'Fieldmapper::asset::copy') {
2337 my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2338 $params->{hold_type} = $type;
2339 } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2340 $params->{hold_type} = 'V';
2341 } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2342 $params->{hold_type} = 'T';
2343 if ($org_unit && ref($org_unit) eq 'Fieldmapper::actor::org_unit') {
2344 $params->{selection_ou} = $org_unit->id();
2345 $params->{depth} = $org_unit->ou_type->depth() if (ref($org_unit->ou_type()));
2349 # Notification params.
2350 if ($do_notification) {
2351 my ($hold_notify) = grep {$_->name() eq 'opac.hold_notify'} @{$user->settings()};
2353 if ($hold_notify->value() =~ /email/) {
2354 $params->{email_notify} = 1;
2356 if ($hold_notify->value() =~ /phone/) {
2357 my ($default_phone) = grep {$_->name() eq 'opac.default_phone'} @{$user->settings()};
2358 # We need to validate the value, because it could be an empty string.
2359 if ($default_phone) {
2360 $default_phone = $default_phone->value();
2361 $default_phone =~ s/"//g;
2363 # Use day phone as fallback if it is empty.
2364 $default_phone = $user->day_phone() unless ($default_phone);
2365 $params->{phone_notify} = $default_phone if ($default_phone);
2367 if ($hold_notify->value() =~ /sms/) {
2368 my ($sms_carrier) = grep {$_->name() eq 'opac.default_sms_carrier'} @{$user->settings()};
2369 my ($sms_notify) = grep {$_->name() eq 'opac.default_sms_notify'} @{$user->settings()};
2370 if ($sms_carrier && $sms_notify) {
2371 # We need to validate the values as well, because
2372 # they can be empty strings.
2373 $sms_carrier = $sms_carrier->value();
2374 $sms_carrier =~ s/"//g;
2375 $sms_notify = $sms_notify->value();
2376 $sms_notify =~ s/"//g;
2377 if ($sms_carrier && $sms_notify) {
2378 $params->{sms_carrier} = $sms_carrier;
2379 $params->{sms_notify} = $sms_notify;
2384 if ($user->email()) {
2385 $params->{email_notify} = 1;
2387 if ($user->day_phone()) {
2388 $params->{phone_notify} = $user->day_phone();
2393 my $response = $U->simplereq(
2395 'open-ils.circ.holds.test_and_create.batch',
2396 $self->{session}->{authtoken},
2401 if (ref($response->{result})) {
2402 my $event = (ref($response->{result}) eq 'ARRAY') ? $response->{result}->[0] : $response->{result}->{last_event};
2403 if ($event->{textcode} eq 'HOLD_EXISTS') {
2404 return NCIP::Problem->new(
2406 ProblemType => 'Duplicate Request',
2407 ProblemDetail => 'A request for this item already exists for this patron.',
2408 ProblemElement => 'NULL',
2409 ProblemValue => 'NULL'
2413 if ($event->{textcode} eq 'ITEM_NOT_HOLDABLE') {
2414 return NCIP::Problem->new(
2416 ProblemType => 'User Ineligible To Request This Item',
2417 ProblemDetail => 'Agency rules prevent the Item from being requested by the User.',
2418 ProblemElement => 'NULL',
2419 ProblemValue => 'NULL'
2423 if ($event->{textcode} eq 'HIGH_LEVEL_HOLD_HAS_NO_COPIES') {
2424 return NCIP::Problem->new(
2426 ProblemType => 'Unknown Item',
2427 ProblemDetail => 'Agency does not have an Item to fill this request.',
2428 ProblemElement => 'NULL',
2429 ProblemValue => 'NULL'
2433 return _problem_from_event('User Ineligible To Request This Item', $event);
2436 # If we make it here, $response->{result} is a hold id.
2437 my $hold = $U->simplereq(
2439 'open-ils.pcrud.retrieve.ahr',
2440 $self->{session}->{authtoken},
2446 =head2 count_eligible_copies
2448 $result = $ils->count_eligible_copies($target, $patron, $pickup_lib, $selection_lib);
2450 This method counts the copies eligible to fill the remote hold on the
2451 target bre for the patron at pickup lib where the copies are owned at
2452 or below the selection lib. It returns the count of copies eligible
2453 to fill the hold at the time of the call, so zero if none are
2454 available or a positive integer otherwise.
2458 sub count_eligible_copies {
2462 my $pickup_lib = shift;
2463 my $selection_lib = shift;
2465 $pickup_lib = $user->home_ou() unless ($pickup_lib);
2467 # To be used in the pcrud query:
2468 my $selection_ou = (ref($selection_lib)) ? $selection_lib->id() : 1;
2470 # Base params for hold is possible check:
2473 patronid => $user->id(),
2474 pickup_lib => $pickup_lib->id()
2477 # return value: count of eligible copies found.
2478 my $eligible_copies = 0;
2480 # pcrud query to find eligible copies:
2481 my $query = {deleted => 'f', circulate => 't', holdable => 't', status => [0,7]};
2482 # Limit copies by call numbers for the target bre:
2483 $query->{call_number} = {
2485 select => {acn => ['id']},
2488 record => $target->id(),
2494 transform => 'actor.org_unit_descendants',
2496 result_field => 'id'
2500 where => {id => $selection_ou}
2506 # Limit copies by circ_lib:
2507 $query->{circ_lib} = {
2512 transform => 'actor.org_unit_descendants',
2513 result_field => 'id'
2517 where => {id => $selection_ou}
2520 # Limit copies by copy locations that allow circ and holds:
2521 $query->{location} = {
2523 select => { acpl => ['id'] },
2525 where => {holdable => 't', circulate => 't'}
2528 # Search for the copies and check each one to see if it could fill the hold.
2529 my $search = OpenSRF::AppSession->create('open-ils.pcrud')->request(
2530 'open-ils.pcrud.search.acp',
2531 $self->{session}->{authtoken},
2534 while (my $response = $search->recv()) {
2535 if ($response->status() eq 'OK') {
2536 my $copy = $response->content();
2537 $params->{copy_id} = $copy->id();
2538 my $result = $U->simplereq(
2540 'open-ils.circ.title_hold.is_possible',
2541 $self->{session}->{authtoken},
2544 if ($result->{success}) {
2551 return $eligible_copies;
2556 $result = $ils->cancel_hold($hold);
2558 This method cancels the hold argument. It makes no checks on the hold,
2559 so if there are certain conditions that need to be fulfilled before
2560 the hold is canceled, then you must check them before calling this
2563 It returns the result of the backend call to cancel the hold: 1 on
2564 succes or an ILS event on failure.
2572 my $r = $U->simplereq(
2574 'open-ils.circ.hold.cancel',
2575 $self->{session}->{authtoken},
2578 'Canceled via NCIPServer'
2584 =head2 abort_transit
2586 $result = $ils->abort_transit($transit);
2588 This method aborts the passed in transit and returns true or false if
2589 it succeeded. In general, we don't care about the return value here,
2590 but subclasses might.
2596 my $transit = shift;
2597 my $result = $U->simplereq(
2599 'open-ils.circ.transit.abort',
2600 $self->{session}->{authtoken},
2601 {transitid => $transit->id()}
2609 =head2 create_hold_note
2611 $note = $ils->create_hold_note($hold, $title, $body);
2613 This method creates a nold note with title of $title and body of $body
2614 on $hold. It is used to store the RequestIdentifierValue from the
2615 RequestItem message so that we can later retrieve holds using that ID
2616 in order to cancel them.
2618 It returns a note object on success and undef on failure.
2622 sub create_hold_note {
2628 my $note = Fieldmapper::action::hold_request_note->new();
2630 $note->hold($hold->id());
2631 $note->title($title);
2636 my $result = $U->simplereq(
2638 'open-ils.circ.hold_request.note.cud',
2639 $self->{session}->{authtoken},
2642 if (not ref($result)) {
2649 =head2 find_hold_via_note
2651 $hold = $ils->find_hold_via_note($title, $body);
2653 Searches for a hold based on a note title and note body. Returns the
2654 hold, and fleshes its transit (if any), if found, undef otherwise.
2655 The search is limited to unfulfilled, uncanceled hold where the
2656 request_lib equals the NCIPServer working org. unit.
2660 sub find_hold_via_note {
2665 # Build the search clause up here, because it is a bit complex.
2671 select => { ahr => ['id']},
2673 where => {cancel_time => undef, fulfillment_time => undef,
2674 request_lib => $self->{session}->{work_ou}->id()}
2679 my $note = $U->simplereq(
2681 'open-ils.pcrud.search.ahrn',
2682 $self->{session}->{authtoken},
2684 {flesh => 2, flesh_fields => {ahrn => ['hold'], ahr => ['transit']}}
2686 if (ref($note) eq 'Fieldmapper::action::hold_request_note') {
2687 return $note->hold();
2695 $ils->delete_copy($copy);
2697 Deletes the copy, and if it is owned by our work_ou and not a precat,
2698 we also delete the volume and bib on which the copy depends.
2706 # Shortcut for ownership checks below.
2707 my $ou_id = $self->{session}->{work_ou}->id();
2709 # First, make sure the copy is not already deleted and we own it.
2710 return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2712 # Indicate we want to delete the copy.
2713 $copy->isdeleted(1);
2714 $copy->deleted('t');
2716 # Delete the copy using a backend call that will delete the copy,
2717 # the call number, and bib when appropriate.
2718 my $result = $U->simplereq(
2720 'open-ils.cat.asset.copy.fleshed.batch.update.override',
2721 $self->{session}->{authtoken},
2725 # We are currently not checking for succes or failure of the
2726 # above. At some point, someone may want to.
2731 =head2 copy_can_circulate
2733 $can_circulate = $ils->copy_can_circulate($copy);
2735 Check if the copy's location and the copy itself allow
2736 circulation. Return true if they do, and false if they do not.
2740 sub copy_can_circulate {
2744 my $location = $copy->location();
2745 unless (ref($location)) {
2746 $location = $self->retrieve_copy_location($location);
2749 return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2752 =head1 OVERRIDDEN PARENT METHODS
2754 =head2 find_user_barcode
2756 We dangerously override our parent's C<find_user_barcode> to return
2757 either the $barcode or a Problem object. In list context the barcode
2758 or problem will be the first argument and the id field, if any, will
2759 be the second. We also add a second, optional, argument to indicate a
2760 default value for the id field in the event of a failure to find
2761 anything at all. (Perl lets us get away with this.)
2765 sub find_user_barcode {
2767 my $request = shift;
2768 my $default = shift;
2771 my $message = $self->parse_request_type($request);
2772 if ($message eq 'LookupUser') {
2773 $default = 'AuthenticationInputData';
2775 $default = 'UserIdentifierValue';
2779 my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2782 $idfield = $default unless ($idfield);
2783 $value = NCIP::Problem->new();
2784 $value->ProblemType('Needed Data Missing');
2785 $value->ProblemDetail('Cannot find user barcode in message.');
2786 $value->ProblemElement($idfield);
2787 $value->ProblemValue('NULL');
2790 return (wantarray) ? ($value, $idfield) : $value;
2793 =head2 find_item_barcode
2795 We do pretty much the same thing as with C<find_user_barcode> for
2796 C<find_item_barcode>.
2800 sub find_item_barcode {
2802 my $request = shift;
2803 my $default = shift || 'ItemIdentifierValue';
2805 my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2808 $idfield = $default unless ($idfield);
2809 $value = NCIP::Problem->new();
2810 $value->ProblemType('Needed Data Missing');
2811 $value->ProblemDetail('Cannot find item barcode in message.');
2812 $value->ProblemElement($idfield);
2813 $value->ProblemValue('NULL');
2816 return (wantarray) ? ($value, $idfield) : $value;
2819 =head2 find_location_failover
2821 $location = $ils->find_location_failover($location, $request, $message);
2823 Attempts to retrieve an org_unit by shortname from the passed in
2824 $location. If that fails, $request and $message are used to lookup
2825 the ToAgencyId/AgencyId field and that is used. Returns an org_unit
2826 as retrieved by retrieve_org_unit_by_shortname if successful and undef
2831 sub find_location_failover {
2832 my ($self, $location, $request, $message) = @_;
2833 if ($request && !$message) {
2834 $message = $self->parse_request_type($request);
2838 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2840 if ($request && $message && !$org_unit) {
2841 $location = $request->{$message}->{InitiationHeader}->{ToAgencyId}->{AgencyId};
2843 $org_unit = $self->retrieve_org_unit_by_shortname($location);
2850 # private subroutines not meant to be used directly by subclasses.
2851 # Most have to do with setup and/or state checking of implementation
2854 # Find, load, and parse our configuration file:
2858 # Find the configuration file via variables:
2859 my $file = OILS_NCIP_CONFIG_DEFAULT;
2860 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2862 $self->{config} = XMLin($file, NormaliseSpace => 2,
2863 ForceArray => ['block_profile', 'stat_cat_entry']);
2866 # Bootstrap OpenSRF::System and load the IDL.
2870 my $bootstrap_config = $self->{config}->{bootstrap};
2871 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2873 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2874 Fieldmapper->import(IDL => $idl);
2877 # Login and then initialize some object data based on the
2882 # Login to Evergreen.
2885 # Load the barred groups as pgt objects into a blocked_profiles
2887 $self->{blocked_profiles} = [];
2888 if (ref($self->{config}->{patrons}) eq 'HASH') {
2889 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2892 $pgt = $U->simplereq(
2894 'open-ils.pcrud.retrieve.pgt',
2895 $self->{session}->{authtoken},
2899 $pgt = $U->simplereq(
2901 'open-ils.pcrud.search.pgt',
2902 $self->{session}->{authtoken},
2907 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2911 # Load the bib source if we're not using precats.
2912 unless ($self->{config}->{items}->{use_precats}) {
2913 # Retrieve the default
2914 $self->{bib_source} = $U->simplereq(
2916 'open-ils.pcrud.retrieve.cbs',
2917 $self->{session}->{authtoken},
2918 BIB_SOURCE_DEFAULT);
2919 my $data = $self->{config}->{items}->{bib_source};
2921 $data = $data->[0] if (ref($data) eq 'ARRAY');
2924 $result = $U->simplereq(
2926 'open-ils.pcrud.retrieve.cbs',
2927 $self->{session}->{authtoken},
2931 $result = $U->simplereq(
2933 'open-ils.pcrud.search.cbs',
2934 $self->{session}->{authtoken},
2938 $self->{bib_source} = $result if ($result);
2942 # Load the required asset.stat_cat_entries:
2943 $self->{stat_cat_entries} = [];
2944 # First, make a regex for our ou and ancestors:
2945 my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2946 my $re = qr/(?:$ancestors)/;
2947 # Get the uniq stat_cat ids from the configuration:
2948 my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2949 # Retrieve all of the fleshed stat_cats and entries for the above.
2950 my $stat_cats = $U->simplereq(
2952 'open-ils.circ.stat_cat.asset.retrieve.batch',
2953 $self->{session}->{authtoken},
2956 foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2957 # Must have the stat_cat attr and the name, so we must have a
2959 next unless(ref $entry);
2960 my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2961 push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2964 # Check if we should abort transits on request cancellation. We
2965 # put this in a different variable because someone may not have
2966 # updated their configuration since this feature was added and we
2967 # don't want runtime errors.
2968 $self->{abort_transit_on_hold_cancel} = 0;
2969 if ($self->{config}->{holds} && $self->{config}->{holds}->{abort_transit_on_cancel}) {
2970 $self->{abort_transit_on_hold_cancel} = 1;
2974 # Search for holds using the user, idvalue and selection_ou.
2979 my $selection_ou = shift;
2983 # Retrieve all of the user's active holds, and then search them in Perl.
2984 my $holds_list = $U->simplereq(
2986 'open-ils.circ.holds.retrieve',
2987 $self->{session}->{authtoken},
2992 if ($holds_list && @$holds_list) {
2993 my @holds = grep {$_->target == $target && $_->selection_ou == $selection_ou->id()} @{$holds_list};
2994 # There should only be 1, at this point, if there are any.
3003 # Standalone, "helper" functions. These do not take an object or
3006 # Check if a user is past their expiration date.
3011 # Users might not expire. If so, they have no expire_date.
3012 if ($user->expire_date()) {
3013 $expired = _date_past($user->expire_date());
3019 # Check if a date has been passed, i.e. is in the past.
3021 # This subroutine was added to have the same functionality of _expired
3022 # without necessitating a change to the _expired subroutine interface
3023 # and the code that already uses it.
3027 my $date_clean = DateTime::Format::ISO8601->parse_datetime(
3028 cleanse_ISO8601($date)
3030 my $now = DateTime->now()->epoch();
3031 return $now > $date_clean;
3034 # Creates a NCIP Problem from an event. Takes a string for the problem
3035 # type, the event hashref (or a string to use for the detail), and
3036 # optional arguments for the ProblemElement and ProblemValue fields.
3037 sub _problem_from_event {
3038 my ($type, $evt, $element, $value) = @_;
3044 my ($textcode, $desc);
3046 # Get the textcode, if available. Otherwise, use the ilsevent
3047 # "id," if available.
3048 if ($evt->{textcode}) {
3049 $textcode = $evt->{textcode};
3050 } elsif ($evt->{ilsevent}) {
3051 $textcode = $evt->{ilsevent};
3054 # Get the description. We favor translated descriptions over
3055 # the English in ils_events.xml.
3057 $desc = $evt->{desc};
3060 # Check if $type was set. As an "undocumented" feature, you
3061 # can pass undef, and we'll use the textcode from the event.
3068 # Set the detail from some combination of the above.
3071 } elsif ($textcode eq 'PERM_FAILURE') {
3072 if ($evt->{ilsperm}) {
3073 $detail = "Permission denied: " . $evt->{ilsperm};
3074 $detail =~ s/\.override$//;
3076 } elsif ($textcode) {
3077 $detail = "ILS returned $textcode error.";
3079 $detail = 'Detail not available.';
3086 return NCIP::Problem->new(
3088 ProblemType => ($type) ? $type : 'Temporary Processing Failure',
3089 ProblemDetail => ($detail) ? $detail : 'Detail not available.',
3090 ProblemElement => ($element) ? $element : 'NULL',
3091 ProblemValue => ($value) ? $value : 'NULL'
3096 # "Fix" dates for output so they validate against the schema
3099 my $out = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($date));
3100 $out->set_time_zone('UTC');
3101 return $out->iso8601();