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;
56 # Inherit from NCIP::ILS.
57 use parent qw(NCIP::ILS);
61 Evergreen - Evergreen driver for NCIPServer
65 my $ils = NCIP::ILS::Evergreen->new(name => $config->{NCIP.ils.value});
69 NCIP::ILS::Evergreen is the default driver for Evergreen and
70 NCIPServer. It was initially developed to work with Auto-Graphics'
71 SHAREit software using a subset of an unspecified ILL/DCB profile.
75 # Default values we define for things that might be missing in our
76 # runtime environment or configuration file that absolutely must have
79 # OILS_NCIP_CONFIG_DEFAULT is the default location to find our
80 # driver's configuration file. This location can be overridden by
81 # setting the path in the OILS_NCIP_CONFIG environment variable.
83 # BIB_SOURCE_DEFAULT is the config.bib_source.id to use when creating
84 # "short" bibs. It is used only if no entry is supplied in the
85 # configuration file. The provided default is 2, the id of the
86 # "System Local" source that comes with a default Evergreen
89 OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
90 BIB_SOURCE_DEFAULT => 2
93 # A common Evergreen code shortcut to use AppUtils:
94 my $U = 'OpenILS::Application::AppUtils';
96 # The usual constructor:
99 $class = ref($class) if (ref $class);
101 # Instantiate our parent with the rest of the arguments. It
102 # creates a blessed hashref.
103 my $self = $class->SUPER::new(@_);
105 # Look for our configuration file, load, and parse it:
108 # Bootstrap OpenSRF and prepare some OpenILS components.
111 # Initialize the rest of our internal state.
117 =head1 HANDLER METHODS
121 $ils->lookupuser($request);
123 Processes a LookupUser request.
131 # Check our session and login if necessary.
132 $self->login() unless ($self->checkauth());
134 my $message_type = $self->parse_request_type($request);
136 # Let's go ahead and create our response object. We need this even
137 # if there is a problem.
138 my $response = NCIP::Response->new({type => $message_type . "Response"});
139 $response->header($self->make_header($request));
141 # Need to parse the request object to get the user barcode.
142 my ($barcode, $idfield) = $self->find_user_barcode($request);
144 # If we did not find a barcode, then report the problem.
145 if (ref($barcode) eq 'NCIP::Problem') {
146 $response->problem($barcode);
150 # Look up our patron by barcode:
151 my $user = $self->retrieve_user_by_barcode($barcode, $idfield);
152 if (ref($user) eq 'NCIP::Problem') {
153 $response->problem($user);
157 # We got the information, so lets fill in our userdata.
158 my $userdata = NCIP::User->new();
160 # Make an array of the user's active barcodes.
162 foreach my $card (@{$user->cards()}) {
163 if ($U->is_true($card->active())) {
164 my $id = NCIP::User::Id->new({
165 UserIdentifierType => 'Barcode',
166 UserIdentifierValue => $card->barcode()
171 $userdata->UserId($ids);
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 = NCIP::User::OptionalFields->new();
179 # First, we'll look for name information.
180 if (grep {$_ eq 'Name Information'} @$elements) {
181 my $name = NCIP::StructuredPersonalUserName->new();
182 $name->Surname($user->family_name());
183 $name->GivenName($user->first_given_name());
184 $name->Prefix($user->prefix());
185 $name->Suffix($user->suffix());
186 $optionalfields->NameInformation($name);
189 # Next, check for user address information.
190 if (grep {$_ eq 'User Address Information'} @$elements) {
193 # See if the user has any valid, physcial addresses.
194 foreach my $addr (@{$user->addresses()}) {
195 next if ($U->is_true($addr->pending()));
196 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
197 my $physical = NCIP::StructuredAddress->new();
198 $physical->Line1($addr->street1());
199 $physical->Line2($addr->street2());
200 $physical->Locality($addr->city());
201 $physical->Region($addr->state());
202 $physical->PostalCode($addr->post_code());
203 $physical->Country($addr->country());
204 $address->PhysicalAddress($physical);
205 push @$addresses, $address;
208 # Right now, we're only sharing email address if the user
209 # has it. We don't share phone numbers.
210 if ($user->email()) {
211 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
212 $address->ElectronicAddress(
213 NCIP::ElectronicAddress->new({
214 Type=>'Email Address',
218 push @$addresses, $address;
221 $optionalfields->UserAddressInformation($addresses);
224 # Check for User Privilege.
225 if (grep {$_ eq 'User Privilege'} @$elements) {
226 # Get the user's group:
227 my $pgt = $U->simplereq(
229 'open-ils.pcrud.retrieve.pgt',
230 $self->{session}->{authtoken},
234 my $privilege = NCIP::User::Privilege->new();
235 $privilege->AgencyId($user->home_ou->shortname());
236 $privilege->AgencyUserPrivilegeType($pgt->name());
237 $privilege->ValidToDate($user->expire_date());
238 $privilege->ValidFromDate($user->create_date());
240 my $status = 'Active';
241 if (_expired($user)) {
243 } elsif ($U->is_true($user->barred())) {
245 } elsif (!$U->is_true($user->active())) {
246 $status = 'Inactive';
249 $privilege->UserPrivilegeStatus(
250 NCIP::User::PrivilegeStatus->new({
251 UserPrivilegeStatusType => $status
256 $optionalfields->UserPrivilege([$privilege]);
260 # Check for Block Or Trap.
261 if (grep {$_ eq 'Block Or Trap'} @$elements) {
264 # First, let's check if the profile is blocked from ILL.
265 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
266 my $block = NCIP::User::BlockOrTrap->new();
267 $block->AgencyId($user->home_ou->shortname());
268 $block->BlockOrTrapType('Block Interlibrary Loan');
269 push @$blocks, $block;
272 # Next, we loop through the user's standing penalties
273 # looking for blocks on CIRC, HOLD, and RENEW.
274 my ($have_circ, $have_renew, $have_hold) = (0,0,0);
275 foreach my $penalty (@{$user->standing_penalties()}) {
276 next unless($penalty->standing_penalty->block_list());
277 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
278 my $ou = $U->simplereq(
280 'open-ils.pcrud.retrieve.aou',
281 $self->{session}->{authtoken},
286 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
287 my $bot = NCIP::User::BlockOrTrap->new();
288 $bot->AgencyId($ou->shortname());
289 $bot->BlockOrTrapType('Block Checkout');
295 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
296 my $bot = NCIP::User::BlockOrTrap->new();
297 $bot->AgencyId($ou->shortname());
298 $bot->BlockOrTrapType('Block Holds');
304 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
305 my $bot = NCIP::User::BlockOrTrap->new();
306 $bot->AgencyId($ou->shortname());
307 $bot->BlockOrTrapType('Block Renewals');
312 # Stop after we report one of each, even if more
314 last if ($have_circ && $have_renew && $have_hold);
317 $optionalfields->BlockOrTrap($blocks);
320 $userdata->UserOptionalFields($optionalfields);
323 $response->data($userdata);
330 $ils->acceptitem($request);
332 Processes an AcceptItem request.
340 # Check our session and login if necessary.
341 $self->login() unless ($self->checkauth());
343 # Common preparation.
344 my $message = $self->parse_request_type($request);
345 my $response = NCIP::Response->new({type => $message . 'Response'});
346 $response->header($self->make_header($request));
348 # We only accept holds for the time being.
349 if ($request->{$message}->{RequestedActionType} !~ /^hold\w/i) {
350 # We need the item id or we can't do anything at all.
351 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
352 if (ref($item_barcode) eq 'NCIP::Problem') {
353 $response->problem($item_barcode);
357 # We need to find a patron barcode or we can't look anyone up
359 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request, 'UserIdentifierValue');
360 if (ref($user_barcode) eq 'NCIP::Problem') {
361 $response->problem($user_barcode);
364 # Look up our patron by barcode:
365 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
366 if (ref($user) eq 'NCIP::Problem') {
367 $response->problem($user);
370 # We're doing patron checks before looking for bibliographic
371 # information and creating the item because problems with the
372 # patron are more likely to occur.
373 my $problem = $self->check_user_for_problems($user, 'HOLD');
375 $response->problem($problem);
379 # Check if the item barcode already exists:
380 my $item = $self->retrieve_copy_details_by_barcode($item_barcode);
382 # What to do here was not defined in the
383 # specification. Since the copies that we create this way
384 # should get deleted when checked in, it would be an error
385 # if we try to create another one. It means that something
386 # has gone wrong somewhere.
390 ProblemType => 'Duplicate Item',
391 ProblemDetail => "Item with barcode $item_barcode already exists.",
392 ProblemElement => $item_idfield,
393 ProblemValue => $item_barcode
400 # Now, we have to create our new copy and/or bib and call number.
402 # First, we have to gather the necessary information from the
403 # request. Store in a hashref for convenience. We may write a
404 # method to get this information in the future if we find we
405 # need it in other handlers. Such a function would be a
406 # candidate to go into our parent, NCIP::ILS.
408 barcode => $item_barcode,
409 call_number => $request->{$message}->{ItemOptionalFields}->{ItemDescription}->{CallNumber},
410 title => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Author},
411 author => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Title},
412 publisher => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Publisher},
413 publication_date => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{PublicationDate},
414 medium => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{MediumType},
415 electronic => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{ElectronicResource}
418 if ($self->{config}->{items}->{use_precats}) {
419 # We only need to create a precat copy.
420 $item = $self->create_precat_copy($item_info);
422 # We have to create a "partial" bib record, a call number and a copy.
423 $item = $self->create_fuller_copy($item_info);
426 # If we failed to create the copy, report a problem.
430 ProblemType => 'Temporary Processing Failure',
431 ProblemDetail => 'Failed to create the item in the system',
432 ProblemElement => $item_idfield,
433 ProblemValue => $item_barcode
439 # We try to find the pickup location in our database. It's OK
440 # if it does not exist, the user's home library will be used
442 my $location = $request->{$message}->{PickupLocation};
444 $location = $self->retrieve_org_unit_by_shortname($location);
447 # Now, we place the hold on the newly created copy on behalf
448 # of the patron retrieved above.
449 my $hold = $self->place_hold($item, $user, $location);
450 if (ref($hold) eq 'NCIP::Problem') {
451 $response->problem($hold);
455 # We return the RequestId and optionally, the ItemID. We'll
456 # just return what was sent to us, since we ignored all of it
459 $data->{RequestId} = NCIP::RequestId->new(
461 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
462 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
463 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
466 $data->{ItemId} = NCIP::Item::Id->new(
468 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
469 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
470 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
473 $response->data($data);
476 my $problem = NCIP::Problem->new();
477 $problem->ProblemType('Unauthorized Combination Of Element Values For System');
478 $problem->ProblemDetail('We only support Hold For Pickup');
479 $problem->ProblemElement('RequestedActionType');
480 $problem->ProblemValue($request->{$message}->{RequestedActionType});
481 $response->problem($problem);
489 $response = $ils->checkinitem($request);
491 Checks the item in if we can find the barcode in the message. It
492 returns problems if it cannot find the item in the system or if the
493 item is not checked out.
495 It could definitely use some more brains at some point as it does not
496 fully support everything that the standard allows. It also does not
497 really check if the checkin succeeded or not.
505 # Check our session and login if necessary:
506 $self->login() unless ($self->checkauth());
509 my $message = $self->parse_request_type($request);
510 my $response = NCIP::Response->new({type => $message . 'Response'});
511 $response->header($self->make_header($request));
513 # We need the copy barcode from the message.
514 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
515 if (ref($item_barcode) eq 'NCIP::Problem') {
516 $response->problem($item_barcode);
520 # Retrieve the copy details.
521 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
523 # Return an Unknown Item problem unless we find the copy.
527 ProblemType => 'Unknown Item',
528 ProblemDetail => "Item with barcode $item_barcode is not known.",
529 ProblemElement => $item_idfield,
530 ProblemValue => $item_barcode
537 # Check if a UserId was provided. If so, this is the patron to
538 # whom the copy should be checked out.
540 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
541 # We ignore the problem, because the UserId is optional.
542 if (ref($user_barcode) ne 'NCIP::Problem') {
543 $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
544 # We don't ignore a problem here, however.
545 if (ref($user) eq 'NCIP::Problem') {
546 $response->problem($user);
552 my $copy = $details->{copy};
554 # Look for a circulation and examine its information:
555 my $circ = $details->{circ};
557 # Check the circ details to see if the copy is checked out and, if
558 # the patron was provided, that it is checked out to the patron in
559 # question. We also verify the copy ownership and circulation
561 my $problem = $self->check_circ_details($circ, $copy, $user);
563 # We need to fill in some information, however.
564 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
565 $problem->ProblemValue($user_barcode);
566 $problem->ProblemElement($user_idfield);
567 } elsif (!$problem->ProblemElement()) {
568 $problem->ProblemElement($item_idfield);
570 $response->problem($problem);
574 # Checkin parameters. We want to skip hold targeting or making
575 # transits, to force the checkin despite the copy status, as
576 # well as void overdues.
578 copy_barcode => $copy->barcode(),
583 my $result = $U->simplereq(
585 'open-ils.circ.checkin.override',
586 $self->{session}->{authtoken},
589 if (ref($result) eq 'ARRAY') {
590 $result = $result->[0];
592 if ($result->{textcode} eq 'SUCCESS') {
593 # Delete the copy. Since delete_copy checks ownership
594 # before attempting to delete the copy, we don't bother
595 # checking who owns it.
596 $self->delete_copy($copy);
597 # We need the circulation user for the information below, so we retrieve it.
598 my $circ_user = $self->retrieve_user_by_id($circ->usr());
600 ItemId => NCIP::Item::Id->new(
602 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
603 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
604 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
607 UserId => NCIP::User::Id->new(
609 UserIdentifierType => 'Barcode Id',
610 UserIdentifierValue => $circ_user->card->barcode()
615 $response->data($data);
617 # At some point in the future, we should probably check if
618 # they requested optional user or item elements and return
619 # those. For the time being, we ignore those at the risk of
620 # being considered non-compliant.
622 $response->problem(_problem_from_event('Checkin Failed', $result));
630 $response = $ils->renewitem($request);
632 Handle the RenewItem message.
640 # Check our session and login if necessary:
641 $self->login() unless ($self->checkauth());
644 my $message = $self->parse_request_type($request);
645 my $response = NCIP::Response->new({type => $message . 'Response'});
646 $response->header($self->make_header($request));
648 # We need the copy barcode from the message.
649 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
650 if (ref($item_barcode) eq 'NCIP::Problem') {
651 $response->problem($item_barcode);
655 # Retrieve the copy details.
656 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
658 # Return an Unknown Item problem unless we find the copy.
662 ProblemType => 'Unknown Item',
663 ProblemDetail => "Item with barcode $item_barcode is not known.",
664 ProblemElement => $item_idfield,
665 ProblemValue => $item_barcode
672 # User is required for RenewItem.
673 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
674 if (ref($user_barcode) eq 'NCIP::Problem') {
675 $response->problem($user_barcode);
678 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
679 if (ref($user) eq 'NCIP::Problem') {
680 $response->problem($user);
685 my $copy = $details->{copy};
687 # Look for a circulation and examine its information:
688 my $circ = $details->{circ};
690 # Check the circ details to see if the copy is checked out and, if
691 # the patron was provided, that it is checked out to the patron in
692 # question. We also verify the copy ownership and circulation
694 my $problem = $self->check_circ_details($circ, $copy, $user);
696 # We need to fill in some information, however.
697 if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
698 $problem->ProblemValue($user_barcode);
699 $problem->ProblemElement($user_idfield);
700 } elsif (!$problem->ProblemElement()) {
701 $problem->ProblemElement($item_idfield);
703 $response->problem($problem);
707 # Check if user is blocked from renewals:
708 $problem = $self->check_user_for_problems($user, 'RENEW');
710 # Replace the ProblemElement and ProblemValue fields.
711 $problem->ProblemElement($user_idfield);
712 $problem->ProblemValue($user_barcode);
713 $response->problem($problem);
717 # Check if the duration rule allows renewals. It should have been
718 # fleshed during the copy details retrieve.
719 my $rule = $circ->duration_rule();
720 unless (ref($rule)) {
721 $rule = $U->simplereq(
723 'open-ils.pcrud.retrieve.crcd',
724 $self->{session}->{authtoken},
728 if ($rule->max_renewals() < 1) {
732 ProblemType => 'Item Not Renewable',
733 ProblemDetail => 'Item may not be renewed.',
734 ProblemElement => $item_idfield,
735 ProblemValue => $item_barcode
742 # Check if there are renewals remaining on the latest circ:
743 if ($circ->renewal_remaining() < 1) {
747 ProblemType => 'Maximum Renewals Exceeded',
748 ProblemDetail => 'Renewal cannot proceed because the User has already renewed the Item the maximum number of times permitted.',
749 ProblemElement => $item_idfield,
750 ProblemValue => $item_barcode
757 # Now, we attempt the renewal. If it fails, we simply say that the
758 # user is not allowed to renew this item, without getting into
762 patron_id => $user->id(),
765 my $r = $U->simplereq(
767 'open-ils.circ.renew.override',
768 $self->{session}->{authtoken},
772 # We only look at the first one, since more than one usually means
774 if (ref($r) eq 'ARRAY') {
777 if ($r->{textcode} ne 'SUCCESS') {
778 $problem = _problem_from_event('Renewal Failed', $r);
779 $response->problem($problem);
782 ItemId => NCIP::Item::Id->new(
784 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
785 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
786 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
789 UserId => NCIP::User::Id->new(
791 UserIdentifierType => 'Barcode Id',
792 UserIdentifierValue => $user->card->barcode()
796 # We need to retrieve the copy details again to refresh our
797 # circ information to get the new due date.
798 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
799 $circ = $details->{circ};
800 my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
801 $due->set_time_zone('UTC');
802 $data->{DateDue} = $due->iso8601();
804 $response->data($data);
807 # At some point in the future, we should probably check if
808 # they requested optional user or item elements and return
809 # those. For the time being, we ignore those at the risk of
810 # being considered non-compliant.
817 $response = $ils->checkoutitem($request);
819 Handle the Checkoutitem message.
827 # Check our session and login if necessary:
828 $self->login() unless ($self->checkauth());
831 my $message = $self->parse_request_type($request);
832 my $response = NCIP::Response->new({type => $message . 'Response'});
833 $response->header($self->make_header($request));
835 # We need the copy barcode from the message.
836 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
837 if (ref($item_barcode) eq 'NCIP::Problem') {
838 $response->problem($item_barcode);
842 # Retrieve the copy details.
843 my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
845 # Return an Unknown Item problem unless we find the copy.
849 ProblemType => 'Unknown Item',
850 ProblemDetail => "Item with barcode $item_barcode is not known.",
851 ProblemElement => $item_idfield,
852 ProblemValue => $item_barcode
859 # User is required for CheckOutItem.
860 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
861 if (ref($user_barcode) eq 'NCIP::Problem') {
862 $response->problem($user_barcode);
865 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
866 if (ref($user) eq 'NCIP::Problem') {
867 $response->problem($user);
872 my $copy = $details->{copy};
874 # Check if the copy can circulate.
875 unless ($self->copy_can_circulate($copy)) {
879 ProblemType => 'Item Does Not Circulate',
880 ProblemDetail => "Item with barcode $item_barcode does not circulate.",
881 ProblemElement => $item_idfield,
882 ProblemValue => $item_barcode
889 # Look for a circulation and examine its information:
890 my $circ = $details->{circ};
892 # Check if the item is already checked out.
893 if ($circ && !$circ->checkin_time()) {
897 ProblemType => 'Item Already Checked Out',
898 ProblemDetail => "Item with barcode $item_barcode is already checked out.",
899 ProblemElement => $item_idfield,
900 ProblemValue => $item_barcode
907 # Check if user is blocked from circulation:
908 my $problem = $self->check_user_for_problems($user, 'CIRC');
910 # Replace the ProblemElement and ProblemValue fields.
911 $problem->ProblemElement($user_idfield);
912 $problem->ProblemValue($user_barcode);
913 $response->problem($problem);
917 # Now, we attempt the check out. If it fails, we simply say that
918 # the user is not allowed to check out this item, without getting
922 patron_id => $user->id(),
924 my $r = $U->simplereq(
926 'open-ils.circ.checkout.full.override',
927 $self->{session}->{authtoken},
931 # We only look at the first one, since more than one usually means
933 if (ref($r) eq 'ARRAY') {
936 if ($r->{textcode} ne 'SUCCESS') {
937 $problem = _problem_from_event('Check Out Failed', $r);
938 $response->problem($problem);
941 ItemId => NCIP::Item::Id->new(
943 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
944 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
945 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
948 UserId => NCIP::User::Id->new(
950 UserIdentifierType => 'Barcode Id',
951 UserIdentifierValue => $user->card->barcode()
955 # We need to retrieve the copy details again to refresh our
956 # circ information to get the due date.
957 $details = $self->retrieve_copy_details_by_barcode($item_barcode);
958 $circ = $details->{circ};
959 my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
960 $due->set_time_zone('UTC');
961 $data->{DateDue} = $due->iso8601();
963 $response->data($data);
966 # At some point in the future, we should probably check if
967 # they requested optional user or item elements and return
968 # those. For the time being, we ignore those at the risk of
969 # being considered non-compliant.
976 $response = $ils->requestitem($request);
978 Handle the NCIP RequestItem message.
985 # Check our session and login if necessary:
986 $self->login() unless ($self->checkauth());
989 my $message = $self->parse_request_type($request);
990 my $response = NCIP::Response->new({type => $message . 'Response'});
991 $response->header($self->make_header($request));
993 # Because we need to have a user to place a hold, because the user
994 # is likely to have problems, and because getting the item
995 # information for the hold is trickier than getting the user
996 # information, we'll do the user first and short circuit out of
997 # the function if there is a problem with the user.
998 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
999 if (ref($user_barcode) eq 'NCIP::Problem') {
1000 $response->problem($user_barcode);
1003 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1004 if (ref($user) eq 'NCIP::Problem') {
1005 $response->problem($user);
1008 my $problem = $self->check_user_for_problems($user, 'HOLD');
1010 $response->problem($problem);
1014 # RequestItem is a blast. We need to check if we have a copy
1015 # barcode and/or if we have BibliographicIds. If we have both or
1016 # either, we then need to figure out what we're placing the hold
1017 # on, a copy, a volume or a bib. We don't currently do part holds,
1018 # but maybe we should some day. We can also be sent more than 1
1019 # BibliographicId, so we look for certain identifiers first, and
1020 # then others in decreasing preference: SYSNUMBER, ISBN, and ISSN.
1022 # Not to mention that there are two kinds of BibliographicId field
1023 # with different field names, and both can be intermixed in an
1024 # incoming message! (I just /love/ this nonsense.)
1026 # This here is the thing we're going to put on hold:
1029 # We need the copy barcode from the message.
1030 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1031 if (ref($item_barcode) ne 'NCIP::Problem') {
1032 # Retrieve the copy details.
1033 my $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1034 unless ($copy_details) {
1035 # Return an Unknown Item problem unless we find the copy.
1039 ProblemType => 'Unknown Item',
1040 ProblemDetail => "Item with barcode $item_barcode is not known.",
1041 ProblemElement => $item_idfield,
1042 ProblemValue => $item_barcode
1048 $item = $copy_details->{volume}; # We place a volume hold.
1051 # We weren't given copy information to target, or we can't find
1052 # it, so we need to look for a target via BibliographicId.
1054 my @biblio_ids = $self->find_bibliographic_ids($request);
1056 $item = $self->find_target_via_bibliographic_id(@biblio_ids);
1060 # If we don't have an item, then blow up with a problem that may
1061 # have been set when we went looking for the ItemId.
1063 if (ref($item_barcode) eq 'NCIP::Problem') {
1064 $response->problem($item_barcode);
1069 ProblemType => 'Request Item Not Found',
1070 ProblemDetail => 'Unable to determine the item to request from input message.',
1071 ProblemElement => 'NULL',
1072 ProblemValue => 'NULL'
1078 } elsif (ref($item) eq 'NCIP::Problem') {
1079 $response->problem($item);
1083 # See if we were given a PickupLocation.
1085 if ($request->{$message}->{PickupLocation}) {
1086 my $loc = $request->{$message}->{PickupLocation};
1087 $loc =~ s/^.*://; # strip everything up to the last
1088 # semi-colon, if any.
1089 $location = $self->retrieve_org_unit_by_shortname($loc);
1093 my $hold = $self->place_hold($item, $user, $location);
1094 if (ref($hold) eq 'NCIP::Problem') {
1095 $response->problem($hold);
1098 RequestId => NCIP::RequestId->new(
1099 RequestIdentifierType => 'SYSNUMBER',
1100 RequestIdentifierValue => $hold->id()
1102 UserId => NCIP::User::Id->new(
1104 UserIdentifierType => 'Barcode Id',
1105 UserIdentifierValue => $user->card->barcode()
1108 RequestType => $request->{$message}->{RequestType},
1109 RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1111 $response->data($data);
1117 =head2 cancelrequestitem
1119 $response = $ils->cancelrequestitem($request);
1121 Handle the NCIP CancelRequestItem message.
1125 sub cancelrequestitem {
1127 my $request = shift;
1128 # Check our session and login if necessary:
1129 $self->login() unless ($self->checkauth());
1132 my $message = $self->parse_request_type($request);
1133 my $response = NCIP::Response->new({type => $message . 'Response'});
1134 $response->header($self->make_header($request));
1136 # UserId is required by the standard, but we might not really need it.
1137 my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1138 if (ref($user_barcode) eq 'NCIP::Problem') {
1139 $response->problem($user_barcode);
1142 my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1143 if (ref($user) eq 'NCIP::Problem') {
1144 $response->problem($user);
1148 # See if we got a ItemId and a barcode:
1150 my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1151 if (ref($item_barcode) ne 'NCIP::Problem') {
1152 # Retrieve the copy details.
1153 $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1154 unless ($copy_details) {
1155 # Return an Unknown Item problem unless we find the copy.
1159 ProblemType => 'Unknown Item',
1160 ProblemDetail => "Item with barcode $item_barcode is not known.",
1161 ProblemElement => $item_idfield,
1162 ProblemValue => $item_barcode
1170 # See if we got a RequestId:
1172 if ($request->{$message}->{RequestId}) {
1173 $requestid = NCIP::RequestId->new(
1175 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1176 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1177 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1182 # Just a note: In the below, we cannot rely on the hold or transit
1183 # fields of the copy_details, even if we have retrieved it. This
1184 # is because that hold and transit may not be the ones that we're
1185 # looking for, i.e. they could be for another patron, etc.
1187 # See if we can find the hold:
1190 $hold = $U->simplereq(
1192 'open-ils.pcrud.retrieve.ahr',
1193 $self->{session}->{authtoken},
1194 $requestid->{RequestIdentifierValue},
1195 {flesh => 1, flesh_fields => {ahr => ['transit']}}
1198 # Report a problem that we couldn't find a hold by that id.
1202 ProblemType => 'Unknown Request',
1203 ProblemDetail => 'No request with this identifier found',
1204 ProblemElement => 'RequestIdentifierValue',
1205 ProblemValue => $requestid->{RequestIdentifierValue}
1209 } elsif ($hold->cancel_time()) {
1213 ProblemType => 'Request Already Canceled',
1214 ProblemDetail => 'Request has already been canceled',
1215 ProblemElement => 'RequestIdentifierValue',
1216 ProblemValue => $requestid->{RequestIdentifierValue}
1220 } elsif ($hold->transit()) {
1224 ProblemType => 'Request Already Processed',
1225 ProblemDetail => 'Request has already been processed',
1226 ProblemElement => 'RequestIdentifierValue',
1227 ProblemValue => $requestid->{RequestIdentifierValue}
1231 } elsif ($hold->usr() == $user->id()) {
1232 # Check the target matches the copy information, if any,
1233 # that we were given.
1235 if ($copy_details) {
1236 if ($hold->hold_type() eq 'V') {
1237 $obj_id = $copy_details->{volume}->id();
1238 } elsif ($hold->hold_type() eq 'T') {
1239 $obj_id = $copy_details->{mvr}->doc_id();
1240 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1241 $obj_id = $copy_details->{copy}->id();
1244 if ($obj_id && $hold->target() != $obj_id) {
1248 ProblemType => 'Request Not For This Item',
1249 ProblemDetail => "Request is not for this item",
1250 ProblemElement => $item_idfield,
1251 ProblemElement => $item_barcode
1256 $self->cancel_hold($hold);
1259 RequestId => $requestid,
1260 UserId => NCIP::User::Id->new(
1262 UserIdentifierType => 'Barcode Id',
1263 UserIdentifierValue => $user->card->barcode()
1270 # Report a problem that the hold is not for this user.
1274 ProblemType => 'Request Not For This User',
1275 ProblemDetail => 'Request is not for this user.',
1276 ProblemElement => $user_idfield,
1277 ProblemValue => $user_barcode
1283 # At this point, we *must have* an ItemId and therefore
1284 # $copy_details, so return the problem from looking up the
1285 # barcode if we don't have $copy_details.
1286 if (!$copy_details) {
1287 $response->problem($item_barcode);
1289 # We have to search for the hold based on the copy details and
1290 # the user. We'll need to search for copy (or force) holds, a
1291 # volume hold, or a title hold.
1292 $hold = $self->_hold_search($user, $copy_details);
1293 if (ref($hold) eq 'NCIP::Problem') {
1294 $response->problem($hold);
1295 } elsif ($hold->transit()) {
1299 ProblemType => 'Request Already Processed',
1300 ProblemDetail => 'Request has already been processed',
1301 ProblemElement => 'RequestIdentifierValue',
1302 ProblemValue => $requestid->{RequestIdentifierValue}
1307 $self->cancel_hold($hold);
1310 RequestId => NCIP::RequestId->new(
1312 RequestIdentifierType => 'SYSNUMBER',
1313 RequestIdentifierValue => $hold->id()
1316 UserId => NCIP::User::Id->new(
1318 UserIdentifierType => 'Barcode Id',
1319 UserIdentifierValue => $user->card->barcode()
1331 =head1 METHODS USEFUL to SUBCLASSES
1337 Login to Evergreen via OpenSRF. It uses internal state from the
1338 configuration file to login.
1342 # Login via OpenSRF to Evergreen.
1346 # Get the authentication seed.
1347 my $seed = $U->simplereq(
1349 'open-ils.auth.authenticate.init',
1350 $self->{config}->{credentials}->{username}
1355 my $response = $U->simplereq(
1357 'open-ils.auth.authenticate.complete',
1359 username => $self->{config}->{credentials}->{username},
1360 password => md5_hex(
1361 $seed . md5_hex($self->{config}->{credentials}->{password})
1364 workstation => $self->{config}->{credentials}->{workstation}
1368 $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1369 $self->{session}->{authtime} = $response->{payload}->{authtime};
1371 # Set/reset the work_ou and user data in case something changed.
1373 # Retrieve the work_ou as an object.
1374 $self->{session}->{work_ou} = $U->simplereq(
1376 'open-ils.pcrud.search.aou',
1377 $self->{session}->{authtoken},
1378 {shortname => $self->{config}->{credentials}->{work_ou}}
1381 # We need the user information in order to do some things.
1382 $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1390 $valid = $ils->checkauth();
1392 Returns 1 if the object a 'valid' authtoken, 0 if not.
1399 # We use AppUtils to do the heavy lifting.
1400 if (defined($self->{session})) {
1401 if ($U->check_user_session($self->{session}->{authtoken})) {
1408 # If we reach here, we don't have a session, so we are definitely
1413 =head2 retrieve_user_by_barcode
1415 $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1417 Do a fleshed retrieve of a patron by barcode. Return the patron if
1418 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1420 The id field argument is used for the ProblemElement field in the
1421 NCIP::Problem object.
1423 An invalid patron is one where the barcode is not found in the
1424 database, the patron is deleted, or the barcode used to retrieve the
1425 patron is not active. The problem element is also returned if an error
1426 occurs during the retrieval.
1430 sub retrieve_user_by_barcode {
1431 my ($self, $barcode, $idfield) = @_;
1432 my $result = $U->simplereq(
1434 'open-ils.actor.user.fleshed.retrieve_by_barcode',
1435 $self->{session}->{authtoken},
1440 # Check for a failure, or a deleted, inactive, or expired user,
1441 # and if so, return empty userdata.
1442 if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1443 || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1445 my $problem = NCIP::Problem->new();
1446 $problem->ProblemType('Unknown User');
1447 $problem->ProblemDetail("User with barcode $barcode unknown");
1448 $problem->ProblemElement($idfield);
1449 $problem->ProblemValue($barcode);
1456 =head2 retrieve_user_by_id
1458 $user = $ils->retrieve_user_by_id($id);
1460 Similar to C<retrieve_user_by_barcode> but takes the user's database
1461 id rather than barcode. This is useful when you have a circulation or
1462 hold and need to get information about the user's involved in the hold
1465 It returns a fleshed user on success or undef on failure.
1469 sub retrieve_user_by_id {
1470 my ($self, $id) = @_;
1472 # Do a fleshed retrieve of the patron, and flesh the fields that
1473 # we would normally use.
1474 my $result = $U->simplereq(
1476 'open-ils.actor.user.fleshed.retrieve',
1477 $self->{session}->{authtoken},
1479 [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1481 # Check for an error.
1482 undef($result) if ($result && $U->event_code($result));
1487 =head2 check_user_for_problems
1489 $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1491 This function checks if a user has a blocked profile or any from a
1492 list of provided blocks. If it does, then a NCIP::Problem object is
1493 returned, otherwise an undefined value is returned.
1495 The list of blocks appears as additional arguments after the user. You
1496 can provide any value(s) that might appear in a standing penalty block
1497 lit in Evergreen. The example above checks for HOLD, CIRC, and
1498 RENEW. Any number of such values can be provided. If none are
1499 provided, the function only checks if the patron's profiles appears in
1500 the object's blocked profiles list.
1502 It stops on the first matching block, if any.
1506 sub check_user_for_problems {
1511 # Fill this in if we have a problem, otherwise just return it.
1514 # First, check the user's profile.
1515 if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1516 $problem = NCIP::Problem->new(
1518 ProblemType => 'User Blocked',
1519 ProblemDetail => 'User blocked from inter-library loan',
1520 ProblemElement => 'NULL',
1521 ProblemValue => 'NULL'
1526 # Next, check if the patron has one of the indicated blocks.
1528 foreach my $block (@blocks) {
1529 if (grep {$_->standing_penalty->block_list() =~ /$block/} @{$user->standing_penalties()}) {
1530 $problem = NCIP::Problem->new(
1532 ProblemType => 'User Blocked',
1533 ProblemDetail => 'User blocked from ' .
1534 ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1535 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1536 ProblemElement => 'NULL',
1537 ProblemValue => 'NULL'
1548 =head2 check_circ_details
1550 $problem = $ils->check_circ_details($circ, $copy, $user);
1552 Checks if we can checkin or renew a circulation. That is, the
1553 circulation is still open (i.e. the copy is still checked out), if we
1554 either own the copy or are the circulation location, and if the
1555 circulation is for the optional $user argument. $circ and $copy are
1556 required. $user is optional.
1558 Returns a problem if any of the above conditions fail. Returns undef
1559 if they pass and we can proceed with the checkin or renewal.
1561 If the failure occurred on the copy-related checks, then the
1562 ProblemElement field will be undefined and needs to be filled in with
1563 the item id field name. If the check for the copy being checked out to
1564 the provided user fails, then both ProblemElement and ProblemValue
1565 fields will be empty and need to be filled in by the caller.
1569 sub check_circ_details {
1570 my ($self, $circ, $copy, $user) = @_;
1572 # Shortcut for the next check.
1573 my $ou_id = $self->{session}->{work_ou}->id();
1575 if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1576 # Item isn't checked out.
1577 return NCIP::Problem->new(
1579 ProblemType => 'Item Not Checked Out',
1580 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1581 ProblemValue => $copy->barcode()
1585 # Get data on the patron who has it checked out.
1586 my $circ_user = $self->retrieve_user_by_id($circ->usr());
1587 if ($user && $circ_user && $user->id() != $circ_user->id()) {
1588 # The ProblemElement and ProblemValue field need to be
1589 # filled in by the caller.
1590 return NCIP::Problem->new(
1592 ProblemType => 'Item Not Checked Out To This User',
1593 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1598 # If we get here, we're good to go.
1602 =head2 retrieve_copy_details_by_barcode
1604 $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1606 Look up and retrieve some copy details by the copy barcode. This
1607 method returns either a hashref with the copy details or undefined if
1608 no copy exists with that barcode or if some error occurs.
1610 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1612 This method differs from C<retrieve_user_by_barcode> in that a copy
1613 cannot be invalid if it exists and it is not always an error if no
1614 copy exists. In some cases, when handling AcceptItem, we might prefer
1615 there to be no copy.
1619 sub retrieve_copy_details_by_barcode {
1621 my $barcode = shift;
1623 my $copy = $U->simplereq(
1625 'open-ils.circ.copy_details.retrieve.barcode',
1626 $self->{session}->{authtoken},
1630 # If $copy is an event, return undefined.
1631 if ($copy && $U->event_code($copy)) {
1638 =head2 retrieve_org_unit_by_shortname
1640 $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1642 Retrieves an org. unit from the database by shortname. Returns the
1643 org. unit as a Fieldmapper object or undefined.
1647 sub retrieve_org_unit_by_shortname {
1649 my $shortname = shift;
1651 my $aou = $U->simplereq(
1653 'open-ils.actor.org_unit.retrieve_by_shortname',
1660 =head2 retrieve_copy_location
1662 $location = $ils->retrieve_copy_location($location_id);
1664 Retrieve a copy location based on id.
1668 sub retrieve_copy_location {
1672 my $location = $U->simplereq(
1674 'open-ils.pcrud.retrieve.acpl',
1675 $self->{session}->{authtoken},
1682 =head2 retrieve_biblio_record_entry
1684 $bre = $ils->retrieve_biblio_record_entry($bre_id);
1686 Given a biblio.record_entry.id, this method retrieves a bre object.
1690 sub retrieve_biblio_record_entry {
1694 my $bre = $U->simplereq(
1696 'open-ils.pcrud.retrieve.bre',
1697 $self->{session}->{authtoken},
1704 =head2 create_precat_copy
1707 barcode => '312340123456789',
1708 author => 'Public, John Q.',
1709 title => 'Magnum Opus',
1710 call_number => '005.82',
1711 publisher => 'Brick House',
1712 publication_date => '2014'
1715 $item = $ils->create_precat_copy($item_info);
1718 Create a "precat" copy to use for the incoming item using a hashref of
1719 item information. At a minimum, the barcode, author and title fields
1720 need to be filled in. The other fields are ignored if provided.
1722 This method is called by the AcceptItem handler if the C<use_precats>
1723 configuration option is turned on.
1727 sub create_precat_copy {
1729 my $item_info = shift;
1731 my $item = Fieldmapper::asset::copy->new();
1732 $item->barcode($item_info->{barcode});
1733 $item->call_number(OILS_PRECAT_CALL_NUMBER);
1734 $item->dummy_title($item_info->{title});
1735 $item->dummy_author($item_info->{author});
1736 $item->circ_lib($self->{session}->{work_ou}->id());
1737 $item->circulate('t');
1738 $item->holdable('t');
1739 $item->opac_visible('f');
1740 $item->deleted('f');
1741 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1742 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1745 $item->editor($self->{session}->{user}->id());
1746 $item->creator($self->{session}->{user}->id());
1749 # Actually create it:
1751 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1754 $xact = $ses->request(
1755 'open-ils.pcrud.transaction.begin',
1756 $self->{session}->{authtoken}
1758 $item = $ses->request(
1759 'open-ils.pcrud.create.acp',
1760 $self->{session}->{authtoken},
1763 $xact = $ses->request(
1764 'open-ils.pcrud.transaction.commit',
1765 $self->{session}->{authtoken}
1773 'open-ils.pcrud.transaction.rollback',
1774 $self->{session}->{authtoken}
1784 =head2 create_fuller_copy
1787 barcode => '31234003456789',
1788 author => 'Public, John Q.',
1789 title => 'Magnum Opus',
1790 call_number => '005.82',
1791 publisher => 'Brick House',
1792 publication_date => '2014'
1795 $item = $ils->create_fuller_copy($item_info);
1797 Creates a skeletal bibliographic record, call number, and copy for the
1798 incoming item using a hashref with item information in it. At a
1799 minimum, the barcode, author, title, and call_number fields must be
1802 This method is used by the AcceptItem handler if the C<use_precats>
1803 configuration option is NOT set.
1807 sub create_fuller_copy {
1809 my $item_info = shift;
1813 # We do everything in one transaction, because it should be atomic.
1814 my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1818 $xact = $ses->request(
1819 'open-ils.pcrud.transaction.begin',
1820 $self->{session}->{authtoken}
1827 # The rest depends on there being a transaction.
1830 # Create the MARC record.
1831 my $record = MARC::Record->new();
1832 $record->encoding('UTF-8');
1833 $record->leader('00881nam a2200193 4500');
1834 my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
1836 push(@fields, MARC::Field->new('005', $datespec));
1837 push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
1838 push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
1839 # Publisher is a little trickier:
1840 if ($item_info->{publisher}) {
1841 my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
1842 $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
1843 push(@fields, $pub);
1845 # We have no idea if the author is personal corporate or something else, so we use a 720.
1846 push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
1847 $record->append_fields(@fields);
1848 my $marc = clean_marc($record);
1850 # Create the bib object.
1851 my $bib = Fieldmapper::biblio::record_entry->new();
1852 $bib->creator($self->{session}->{user}->id());
1853 $bib->editor($self->{session}->{user}->id());
1854 $bib->source($self->{bib_source}->id());
1861 $bib = $ses->request(
1862 'open-ils.pcrud.create.bre',
1863 $self->{session}->{authtoken},
1871 'open-ils.pcrud.transaction.rollback',
1872 $self->{session}->{authtoken}
1877 # Create the call number
1880 $acn = Fieldmapper::asset::call_number->new();
1881 $acn->creator($self->{session}->{user}->id());
1882 $acn->editor($self->{session}->{user}->id());
1883 $acn->label($item_info->{call_number});
1884 $acn->record($bib->id());
1885 $acn->owning_lib($self->{session}->{work_ou}->id());
1890 $acn = $ses->request(
1891 'open-ils.pcrud.create.acn',
1892 $self->{session}->{authtoken},
1900 'open-ils.pcrud.transaction.rollback',
1901 $self->{session}->{authtoken}
1909 $item = Fieldmapper::asset::copy->new();
1910 $item->barcode($item_info->{barcode});
1911 $item->call_number($acn->id());
1912 $item->circ_lib($self->{session}->{work_ou}->id);
1913 $item->circulate('t');
1914 if ($self->{config}->{items}->{use_force_holds}) {
1915 $item->holdable('f');
1917 $item->holdable('t');
1919 $item->opac_visible('f');
1920 $item->deleted('f');
1921 $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1922 $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1925 $item->editor($self->{session}->{user}->id);
1926 $item->creator($self->{session}->{user}->id);
1930 $item = $ses->request(
1931 'open-ils.pcrud.create.acp',
1932 $self->{session}->{authtoken},
1936 # Cross our fingers and commit the work.
1937 $xact = $ses->request(
1938 'open-ils.pcrud.transaction.commit',
1939 $self->{session}->{authtoken}
1946 'open-ils.pcrud.transaction.rollback',
1947 $self->{session}->{authtoken}
1948 )->gather(1) if ($xact);
1954 # We need to disconnect our session.
1957 # Now, we handle our asset stat_cat entries.
1959 # It would be nice to do these in the above transaction, but
1960 # pcrud does not support the ascecm object, yet.
1961 foreach my $entry (@{$self->{stat_cat_entries}}) {
1962 my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1964 $map->stat_cat($entry->stat_cat());
1965 $map->stat_cat_entry($entry->id());
1966 $map->owning_copy($item->id());
1967 # We don't really worry if it succeeds or not.
1970 'open-ils.circ.stat_cat.asset.copy_map.create',
1971 $self->{session}->{authtoken},
1982 $hold = $ils->place_hold($item, $user, $location);
1984 This function places a hold on $item for $user for pickup at
1985 $location. If location is not provided or undefined, the user's home
1986 library is used as a fallback.
1988 $item can be a copy (asset::copy), volume (asset::call_number), or bib
1989 (biblio::record_entry). The appropriate hold type will be placed
1990 depending on the object.
1992 On success, the method returns the object representing the hold. On
1993 failure, a NCIP::Problem object, describing the failure, is returned.
2001 my $location = shift;
2003 # If $location is undefined, use the user's home_ou, which should
2004 # have been fleshed when the user was retrieved.
2005 $location = $user->home_ou() unless ($location);
2007 # $hold is the hold. $params is for the is_possible check.
2008 my ($hold, $params);
2010 # Prep the hold with fields common to all hold types:
2011 $hold = Fieldmapper::action::hold_request->new();
2012 $hold->isnew(1); # Just to make sure.
2013 $hold->target($item->id());
2014 $hold->usr($user->id());
2015 $hold->pickup_lib($location->id());
2016 if (!$user->email()) {
2017 $hold->email_notify('f');
2018 $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2020 $hold->email_notify('t');
2024 $params = { pickup_lib => $location->id(), patronid => $user->id() };
2026 if (ref($item) eq 'Fieldmapper::asset::copy') {
2027 my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2028 $hold->hold_type($type);
2029 $hold->current_copy($item->id());
2030 $params->{hold_type} = $type;
2031 $params->{copy_id} = $item->id();
2032 } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2033 $hold->hold_type('V');
2034 $params->{hold_type} = 'V';
2035 $params->{volume_id} = $item->id();
2036 } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2037 $hold->hold_type('T');
2038 $params->{hold_type} = 'T';
2039 $params->{titleid} = $item->id();
2042 # Check for a duplicate hold:
2043 my $duplicate = $U->simplereq(
2045 'open-ils.pcrud.search.ahr',
2046 $self->{session}->{authtoken},
2048 hold_type => $hold->hold_type(),
2049 target => $hold->target(),
2050 usr => $hold->usr(),
2051 expire_time => {'>' => 'now'},
2052 cancel_time => undef,
2053 fulfillment_time => undef
2057 return NCIP::Problem->new(
2059 ProblemType => 'Duplicate Request',
2060 ProblemDetail => 'A request for this item already exists for this patron.',
2061 ProblemElement => 'NULL',
2062 ProblemValue => 'NULL'
2067 # Check if the hold is possible:
2068 my $r = $U->simplereq(
2070 'open-ils.circ.title_hold.is_possible',
2071 $self->{session}->{authtoken},
2075 if ($r->{success}) {
2076 $hold = $U->simplereq(
2078 'open-ils.circ.holds.create.override',
2079 $self->{session}->{authtoken},
2082 if (ref($hold) eq 'HASH') {
2083 $hold = _problem_from_event('Request Not Possible', $hold);
2085 } elsif ($r->{last_event}) {
2086 $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2087 } elsif ($r->{textcode}) {
2088 $hold = _problem_from_event('Request Not Possible', $r);
2090 $hold = _problem_from_event('Request Not Possible');
2098 $ils->cancel_hold($hold);
2100 This method cancels the hold argument. It makes no checks on the hold,
2101 so if there are certain conditions that need to be fulfilled before
2102 the hold is canceled, then you must check them before calling this
2105 It returns undef on success or failure. If it fails, you've usually
2106 got bigger problems.
2114 my $r = $U->simplereq(
2116 'open-ils.circ.hold.cancel',
2117 $self->{session}->{authtoken},
2120 'Canceled via NCIPServer'
2128 $ils->delete_copy($copy);
2130 Deletes the copy, and if it is owned by our work_ou and not a precat,
2131 we also delete the volume and bib on which the copy depends.
2139 # Shortcut for ownership checks below.
2140 my $ou_id = $self->{session}->{work_ou}->id();
2142 # First, make sure the copy is not already deleted and we own it.
2143 return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2145 # Indicate we want to delete the copy.
2146 $copy->isdeleted(1);
2148 # Delete the copy using a backend call that will delete the copy,
2149 # the call number, and bib when appropriate.
2150 my $result = $U->simplereq(
2152 'open-ils.cat.asset.copy.fleshed.batch.update.override',
2153 $self->{session}->{authtoken},
2157 # We are currently not checking for succes or failure of the
2158 # above. At some point, someone may want to.
2163 =head2 copy_can_circulate
2165 $can_circulate = $ils->copy_can_circulate($copy);
2167 Check if the copy's location and the copy itself allow
2168 circulation. Return true if they do, and false if they do not.
2172 sub copy_can_circulate {
2176 my $location = $copy->location();
2177 unless (ref($location)) {
2178 $location = $self->retrieve_copy_location($location);
2181 return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2184 =head2 copy_can_fulfill
2186 $can_fulfill = $ils->copy_can_fulfill($copy);
2188 Check if the copy's location and the copy itself allow
2189 holds. Return true if they do, and false if they do not.
2193 sub copy_can_fulfill {
2197 my $location = $copy->location();
2198 unless (ref($location)) {
2199 $location = $self->retrieve_copy_location($location);
2202 return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2205 =head1 OVERRIDDEN PARENT METHODS
2207 =head2 find_user_barcode
2209 We dangerously override our parent's C<find_user_barcode> to return
2210 either the $barcode or a Problem object. In list context the barcode
2211 or problem will be the first argument and the id field, if any, will
2212 be the second. We also add a second, optional, argument to indicate a
2213 default value for the id field in the event of a failure to find
2214 anything at all. (Perl lets us get away with this.)
2218 sub find_user_barcode {
2220 my $request = shift;
2221 my $default = shift;
2224 my $message = $self->parse_request_type($request);
2225 if ($message eq 'LookupUser') {
2226 $default = 'AuthenticationInputData';
2228 $default = 'UserIdentifierValue';
2232 my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2235 $idfield = $default unless ($idfield);
2236 $value = NCIP::Problem->new();
2237 $value->ProblemType('Needed Data Missing');
2238 $value->ProblemDetail('Cannot find user barcode in message.');
2239 $value->ProblemElement($idfield);
2240 $value->ProblemValue('NULL');
2243 return (wantarray) ? ($value, $idfield) : $value;
2246 =head2 find_item_barcode
2248 We do pretty much the same thing as with C<find_user_barcode> for
2249 C<find_item_barcode>.
2253 sub find_item_barcode {
2255 my $request = shift;
2256 my $default = shift || 'ItemIdentifierValue';
2258 my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2261 $idfield = $default unless ($idfield);
2262 $value = NCIP::Problem->new();
2263 $value->ProblemType('Needed Data Missing');
2264 $value->ProblemDetail('Cannot find item barcode in message.');
2265 $value->ProblemElement($idfield);
2266 $value->ProblemValue('NULL');
2269 return (wantarray) ? ($value, $idfield) : $value;
2272 =head2 find_target_via_bibliographic_id
2274 $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2276 Searches for a bibliographic record to put on hold and returns an
2277 appropriate hold target item depending upon what it finds. If an
2278 appropriate, single target cannot be found, it returns an
2279 NCIP::Problem with the problem message.
2281 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2282 identifiers. If nothing is found, this method can return undef. (Gotta
2283 love Perl and untyped/weakly typed languages in general!)
2285 TODO: Figure out how to search OCLC numbers. We probably need to use
2286 "MARC Expert Search" if we don't want to do a JSON query on
2291 sub find_target_via_bibliographid_id {
2293 my @biblio_ids = @_;
2295 # The item that we find:
2298 # Id for our bib in Evergreen:
2301 # First, let's look for a SYSNUMBER:
2303 { $_->{BibligraphicRecordIdentifierCode} eq 'SYSNUMBER' || $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER'
2308 # BibliographicRecordId can have an AgencyId field if the
2309 # BibliographicRecordIdentifierCode is absent.
2310 if ($idobj->{AgencyId}) {
2311 $bibid = $idobj->{BibliographicRecordIdentifier};
2312 my $locname = $idobj->{AgencyId};
2314 $locname =~ s/.*://;
2315 $loc = $self->retrieve_org_unit_by_shortname($locname);
2317 } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2318 $bibid = $idobj->{BibliographicRecordIdentifierCode}
2320 $bibid = $idobj->{BibliographicItemIdentifierCode}
2322 if ($bibid && $loc) {
2323 $item = $self->_call_number_search($bibid, $loc);
2325 $item = $U->simplereq(
2327 'open-ils.pcrud.retrieve.bre',
2328 $self->{session}->{authtoken},
2332 # Check if item is deleted so we'll look for more
2334 undef($item) if ($item && $U->is_true($item->deleted()));
2337 # Build an array of id objects based on the other identifier fields.
2340 $_->{BibliographicRecordIdentifierCode} eq 'ISBN' || $_->{BibliographicItemIdentifierCode} eq 'ISBN'
2342 $_->{BibliographicRecordIdentifierCode} eq 'ISSN' || $_->{BibliographicItemIdentifierCode} eq 'ISSN'
2346 my $stashed_problem;
2347 # Reuse $idobj from above.
2348 foreach $idobj (@idobjs) {
2349 my ($idvalue, $idtype, $idfield);
2350 if ($_->{BibliographicItemIdentifier}) {
2351 $idvalue = $_->{BibliographicItemIdentifier};
2352 $idtype = $_->{BibliographicItemIdentifierCode};
2353 $idfield = 'BibliographicItemIdentifier';
2355 $idvalue = $_->{BibliographicRecordIdentifier};
2356 $idtype = $_->{BibliographicRecordIdentifierCode};
2357 $idfield = 'BibliographicRecordIdentifier';
2359 $item = $self->_bib_search($idvalue, $idtype);
2360 if (ref($item) eq 'NCIP::Problem') {
2361 $stashed_problem = $item unless($stashed_problem);
2362 $stashed_problem->ProblemElement($idfield);
2367 $item = $stashed_problem if (!$item && $stashed_problem);
2373 # private subroutines not meant to be used directly by subclasses.
2374 # Most have to do with setup and/or state checking of implementation
2377 # Find, load, and parse our configuration file:
2381 # Find the configuration file via variables:
2382 my $file = OILS_NCIP_CONFIG_DEFAULT;
2383 $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2385 $self->{config} = XMLin($file, NormaliseSpace => 2,
2386 ForceArray => ['block_profile', 'stat_cat_entry']);
2389 # Bootstrap OpenSRF::System and load the IDL.
2393 my $bootstrap_config = $self->{config}->{bootstrap};
2394 OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2396 my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2397 Fieldmapper->import(IDL => $idl);
2400 # Login and then initialize some object data based on the
2405 # Login to Evergreen.
2408 # Load the barred groups as pgt objects into a blocked_profiles
2410 $self->{blocked_profiles} = [];
2411 foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2414 $pgt = $U->simplereq(
2416 'open-ils.pcrud.retrieve.pgt',
2417 $self->{session}->{authtoken},
2421 $pgt = $U->simplereq(
2423 'open-ils.pcrud.search.pgt',
2424 $self->{session}->{authtoken},
2428 push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2431 # Load the bib source if we're not using precats.
2432 unless ($self->{config}->{items}->{use_precats}) {
2433 # Retrieve the default
2434 $self->{bib_source} = $U->simplereq(
2436 'open-ils.pcrud.retrieve.cbs',
2437 $self->{session}->{authtoken},
2438 BIB_SOURCE_DEFAULT);
2439 my $data = $self->{config}->{items}->{bib_source};
2441 $data = $data->[0] if (ref($data) eq 'ARRAY');
2444 $result = $U->simplereq(
2446 'open-ils.pcrud.retrieve.cbs',
2447 $self->{session}->{authtoken},
2451 $result = $U->simplereq(
2453 'open-ils.pcrud.search.cbs',
2454 $self->{session}->{authtoken},
2458 $self->{bib_source} = $result if ($result);
2462 # Load the required asset.stat_cat_entries:
2463 $self->{stat_cat_entries} = [];
2464 # First, make a regex for our ou and ancestors:
2465 my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2466 my $re = qr/(?:$ancestors)/;
2467 # Get the uniq stat_cat ids from the configuration:
2468 my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2469 # Retrieve all of the fleshed stat_cats and entries for the above.
2470 my $stat_cats = $U->simplereq(
2472 'open-ils.circ.stat_cat.asset.retrieve.batch',
2473 $self->{session}->{authtoken},
2476 foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2477 # Must have the stat_cat attr and the name, so we must have a
2479 next unless(ref $entry);
2480 my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2481 push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2485 # Search asset.call_number by a bre.id and location object. Return the
2486 # "closest" call_number if found, undef otherwise.
2487 sub _call_number_search {
2490 my $location = shift;
2492 # At some point, this should be smarter, and we should retrieve
2493 # ancestors and descendants and search with a JSON query or some
2494 # such with results ordered by proximity to the original location,
2495 # but I don't have time to implement that right now.
2496 my $acn = $U->simplereq(
2498 'open-ils.pcrud.search.acn',
2499 $self->{session}->{authtoken},
2500 {record => $bibid, owning_lib => $location->id()}
2506 # Do a multiclass.query to search for items by isbn or issn.
2509 my $idvalue = shift;
2513 my $result = $U->simplereq(
2515 'open-ils.search.biblio.multiclass',
2516 {searches => {lc($idtype) => $idvalue}}
2519 if ($result && $result->{count}) {
2520 if ($result->{count} > 1) {
2521 $item = NCIP::Problem->new(
2523 ProblemType => 'Non-Unique Item',
2524 ProblemDetail => 'More than one item matches the request.',
2525 ProblemElement => '',
2526 ProblemValue => $idvalue
2530 my $bibid = $result->{ids}->[0]->[0];
2531 $item = $U->simplereq(
2533 'open-ils.pcrud.retrieve.bre',
2534 $self->{session}->{authtoken},
2542 # Search for holds using the user and copy_details information:
2546 my $copy_details = shift;
2550 # Retrieve all of the user's uncanceled, unfulfilled holds, and
2551 # then search them in Perl.
2552 my $holds_list = $U->simplereq(
2554 'open-ils.circ.holds.retrieve',
2555 $self->{session}->{authtoken},
2560 if ($holds_list && @$holds_list) {
2562 # Look for title holds (the most common), first:
2563 my $targetid = $copy_details->{mvr}->doc_id();
2564 @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2566 # Look for volume holds, the next most common:
2567 $targetid = $copy_details->{volume}->id();
2568 @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2571 # Look for copy and force holds, the least likely.
2572 $targetid = $copy_details->{copy}->id();
2573 @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
2575 # There should only be 1, at this point, if there are any.
2582 $hold = NCIP::Problem->new(
2584 ProblemType => 'Unknown Request',
2585 ProblemDetail => 'Request matching the user and item not found.',
2586 ProblemElement => 'NULL',
2587 ProblemValue => 'NULL'
2595 # Standalone, "helper" functions. These do not take an object or
2598 # Check if a user is past their expiration date.
2603 # Users might not expire. If so, they have no expire_date.
2604 if ($user->expire_date()) {
2605 my $expires = DateTime::Format::ISO8601->parse_datetime(
2606 cleanse_ISO8601($user->expire_date())
2608 my $now = DateTime->now()->epoch();
2609 $expired = $now > $expires;
2615 # Creates a NCIP Problem from an event. Takes a string for the problem
2616 # type, the event hashref (or a string to use for the detail), and
2617 # optional arguments for the ProblemElement and ProblemValue fields.
2618 sub _problem_from_event {
2619 my ($type, $evt, $element, $value) = @_;
2625 my ($textcode, $desc);
2627 # Get the textcode, if available. We favor those defined in
2628 # ils_events.xml over those made up on the fly.
2629 if ($evt->{ilsevent} && $evt->{ilsevent}->{textcode}) {
2630 $textcode = $evt->{ilsevent}->{textcode};
2631 } elsif ($evt->{textcode}) {
2632 $textcode = $evt->{textcode};
2635 # Get the description. We favor translated descriptions over
2636 # the English in ils_events.xml.
2638 $desc = $evt->{desc};
2639 } elsif ($evt->{ilsevent} && $evt->{ilsevent}->{desc}) {
2640 $desc = $evt->{ilsevent}->{desc};
2643 # Check if $type was set. As an "undocumented" feature, you
2644 # can pass undef, and we'll use the textcode from the event.
2651 # Set the detail from some combination of the above.
2654 } elsif ($textcode eq 'PERM_FAILURE') {
2655 if ($evt->{ilsperm}) {
2656 $detail = "Permission denied: " . $evt->{ilsperm};
2657 $detail =~ s/\.override$//;
2659 } elsif ($textcode) {
2660 $detail = "ILS returned $textcode error.";
2662 $detail = 'Detail not available.';
2669 return NCIP::Problem->new(
2671 ProblemType => ($type) ? $type : 'Temporary Processing Failure',
2672 ProblemDetail => ($detail) ? $detail : 'Detail not available.',
2673 ProblemElement => ($element) ? $element : 'NULL',
2674 ProblemValue => ($value) ? $value : 'NULL'