]> git.evergreen-ils.org Git - working/NCIPServer.git/blob - lib/NCIP/ILS/Evergreen.pm
Add handling of NeedBeforeDate to NCIP::ILS::Evergreen->requestitem.
[working/NCIPServer.git] / lib / NCIP / ILS / Evergreen.pm
1 # ---------------------------------------------------------------
2 # Copyright © 2014 Jason J.A. Stephenson <jason@sigio.com>
3 #
4 # This file is part of NCIPServer.
5 #
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.
10 #
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.
15 #
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;
20
21 use Modern::Perl;
22 use XML::LibXML::Simple qw(XMLin);
23 use DateTime;
24 use DateTime::Format::ISO8601;
25 use Digest::MD5 qw/md5_hex/;
26 use OpenSRF::System;
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/;
34 use MARC::Record;
35 use MARC::Field;
36 use MARC::File::XML;
37 use List::MoreUtils qw/uniq/;
38 use POSIX qw/strftime/;
39
40 # We need a bunch of NCIP::* objects.
41 use NCIP::Response;
42 use NCIP::Problem;
43 use NCIP::User;
44 use NCIP::User::OptionalFields;
45 use NCIP::User::AddressInformation;
46 use NCIP::User::Id;
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::RequestId;
54 use NCIP::Item::Id;
55
56 # Inherit from NCIP::ILS.
57 use parent qw(NCIP::ILS);
58
59 =head1 NAME
60
61 Evergreen - Evergreen driver for NCIPServer
62
63 =head1 SYNOPSIS
64
65     my $ils = NCIP::ILS::Evergreen->new(name => $config->{NCIP.ils.value});
66
67 =head1 DESCRIPTION
68
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.
72
73 =cut
74
75 # Default values we define for things that might be missing in our
76 # runtime environment or configuration file that absolutely must have
77 # values.
78 #
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.
82 #
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
87 # installation.
88 use constant {
89     OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
90     BIB_SOURCE_DEFAULT => 2
91 };
92
93 # A common Evergreen code shortcut to use AppUtils:
94 my $U = 'OpenILS::Application::AppUtils';
95
96 # The usual constructor:
97 sub new {
98     my $class = shift;
99     $class = ref($class) if (ref $class);
100
101     # Instantiate our parent with the rest of the arguments.  It
102     # creates a blessed hashref.
103     my $self = $class->SUPER::new(@_);
104
105     # Look for our configuration file, load, and parse it:
106     $self->_configure();
107
108     # Bootstrap OpenSRF and prepare some OpenILS components.
109     $self->_bootstrap();
110
111     # Initialize the rest of our internal state.
112     $self->_init();
113
114     return $self;
115 }
116
117 =head1 HANDLER METHODS
118
119 =head2 lookupuser
120
121     $ils->lookupuser($request);
122
123 Processes a LookupUser request.
124
125 =cut
126
127 sub lookupuser {
128     my $self = shift;
129     my $request = shift;
130
131     # Check our session and login if necessary.
132     $self->login() unless ($self->checkauth());
133
134     my $message_type = $self->parse_request_type($request);
135
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));
140
141     # Need to parse the request object to get the user barcode.
142     my ($barcode, $idfield) = $self->find_user_barcode($request);
143
144     # If we did not find a barcode, then report the problem.
145     if (ref($barcode) eq 'NCIP::Problem') {
146         $response->problem($barcode);
147         return $response;
148     }
149
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);
154         return $response;
155     }
156
157     # We got the information, so lets fill in our userdata.
158     my $userdata = NCIP::User->new();
159
160     # Make an array of the user's active barcodes.
161     my $ids = [];
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()
167             });
168             push(@$ids, $id);
169         }
170     }
171     $userdata->UserId($ids);
172
173     # Check if they requested any optional fields and return those.
174     my $elements = $request->{$message_type}->{UserElementType};
175     if ($elements) {
176         $elements = [$elements] unless (ref $elements eq 'ARRAY');
177         my $optionalfields = NCIP::User::OptionalFields->new();
178
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);
187         }
188
189         # Next, check for user address information.
190         if (grep {$_ eq 'User Address Information'} @$elements) {
191             my $addresses = [];
192
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;
206             }
207
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',
215                         Data=>$user->email()
216                     })
217                 );
218                 push @$addresses, $address;
219             }
220
221             $optionalfields->UserAddressInformation($addresses);
222         }
223
224         # Check for User Privilege.
225         if (grep {$_ eq 'User Privilege'} @$elements) {
226             # Get the user's group:
227             my $pgt = $U->simplereq(
228                 'open-ils.pcrud',
229                 'open-ils.pcrud.retrieve.pgt',
230                 $self->{session}->{authtoken},
231                 $user->profile()
232             );
233             if ($pgt) {
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());
239
240                 my $status = 'Active';
241                 if (_expired($user)) {
242                     $status = 'Expired';
243                 } elsif ($U->is_true($user->barred())) {
244                     $status = 'Barred';
245                 } elsif (!$U->is_true($user->active())) {
246                     $status = 'Inactive';
247                 }
248                 if ($status) {
249                     $privilege->UserPrivilegeStatus(
250                         NCIP::User::PrivilegeStatus->new({
251                             UserPrivilegeStatusType => $status
252                         })
253                     );
254                 }
255
256                 $optionalfields->UserPrivilege([$privilege]);
257             }
258         }
259
260         # Check for Block Or Trap.
261         if (grep {$_ eq 'Block Or Trap'} @$elements) {
262             my $blocks = [];
263
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;
270             }
271
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(
279                     'open-ils.pcrud',
280                     'open-ils.pcrud.retrieve.aou',
281                     $self->{session}->{authtoken},
282                     $penalty->org_unit()
283                 );
284
285                 # Block checkout.
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');
290                     push @$blocks, $bot;
291                     $have_circ = 1;
292                 }
293
294                 # Block holds.
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');
299                     push @$blocks, $bot;
300                     $have_hold = 1;
301                 }
302
303                 # Block renewals.
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');
308                     push @$blocks, $bot;
309                     $have_renew = 1;
310                 }
311
312                 # Stop after we report one of each, even if more
313                 # blocks remain.
314                 last if ($have_circ && $have_renew && $have_hold);
315             }
316
317             $optionalfields->BlockOrTrap($blocks);
318         }
319
320         $userdata->UserOptionalFields($optionalfields);
321     }
322
323     $response->data($userdata);
324
325     return $response;
326 }
327
328 =head2 acceptitem
329
330     $ils->acceptitem($request);
331
332 Processes an AcceptItem request.
333
334 =cut
335
336 sub acceptitem {
337     my $self = shift;
338     my $request = shift;
339
340     # Check our session and login if necessary.
341     $self->login() unless ($self->checkauth());
342
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));
347
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);
354             return $response;
355         }
356
357         # We need to find a patron barcode or we can't look anyone up
358         # to place a hold.
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);
362             return $response;
363         }
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);
368             return $response;
369         }
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');
374         if ($problem) {
375             $response->problem($problem);
376             return $response;
377         }
378
379         # Check if the item barcode already exists:
380         my $item = $self->retrieve_copy_details_by_barcode($item_barcode);
381         if ($item) {
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.
387             $response->problem(
388                 NCIP::Problem->new(
389                     {
390                         ProblemType => 'Duplicate Item',
391                         ProblemDetail => "Item with barcode $item_barcode already exists.",
392                         ProblemElement => $item_idfield,
393                         ProblemValue => $item_barcode
394                     }
395                 )
396             );
397             return $response;
398         }
399
400         # Now, we have to create our new copy and/or bib and call number.
401
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.
407         my $item_info = {
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}
416         };
417
418         if ($self->{config}->{items}->{use_precats}) {
419             # We only need to create a precat copy.
420             $item = $self->create_precat_copy($item_info);
421         } else {
422             # We have to create a "partial" bib record, a call number and a copy.
423             $item = $self->create_fuller_copy($item_info);
424         }
425
426         # If we failed to create the copy, report a problem.
427         unless ($item) {
428             $response->problem(
429                 {
430                     ProblemType => 'Temporary Processing Failure',
431                     ProblemDetail => 'Failed to create the item in the system',
432                     ProblemElement => $item_idfield,
433                     ProblemValue => $item_barcode
434                 }
435             );
436             return $response;
437         }
438
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
441         # instead.
442         my $location = $request->{$message}->{PickupLocation};
443         if ($location) {
444             $location = $self->retrieve_org_unit_by_shortname($location);
445         }
446
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);
452             return $response;
453         }
454
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
457         # but the barcode.
458         my $data = {};
459         $data->{RequestId} = NCIP::RequestId->new(
460             {
461                 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
462                 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
463                 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
464             }
465         );
466         $data->{ItemId} = NCIP::Item::Id->new(
467             {
468                 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
469                 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
470                 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
471             }
472         );
473         $response->data($data);
474
475     } else {
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);
482     }
483
484     return $response;
485 }
486
487 =head2 checkinitem
488
489     $response = $ils->checkinitem($request);
490
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.
494
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.
498
499 =cut
500
501 sub checkinitem {
502     my $self = shift;
503     my $request = shift;
504
505     # Check our session and login if necessary:
506     $self->login() unless ($self->checkauth());
507
508     # Common stuff:
509     my $message = $self->parse_request_type($request);
510     my $response = NCIP::Response->new({type => $message . 'Response'});
511     $response->header($self->make_header($request));
512
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);
517         return $response;
518     }
519
520     # Retrieve the copy details.
521     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
522     unless ($details) {
523         # Return an Unknown Item problem unless we find the copy.
524         $response->problem(
525             NCIP::Problem->new(
526                 {
527                     ProblemType => 'Unknown Item',
528                     ProblemDetail => "Item with barcode $item_barcode is not known.",
529                     ProblemElement => $item_idfield,
530                     ProblemValue => $item_barcode
531                 }
532             )
533         );
534         return $response;
535     }
536
537     # Check if a UserId was provided. If so, this is the patron to
538     # whom the copy should be checked out.
539     my $user;
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);
547             return $response;
548         }
549     }
550
551     # Isolate the copy.
552     my $copy = $details->{copy};
553
554     # Look for a circulation and examine its information:
555     my $circ = $details->{circ};
556
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
560     # location.
561     my $problem = $self->check_circ_details($circ, $copy, $user);
562     if ($problem) {
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);
569         }
570         $response->problem($problem);
571         return $response;
572     }
573
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.
577     my $params = {
578         copy_barcode => $copy->barcode(),
579         force => 1,
580         noop => 1,
581         void_overdues => 1
582     };
583     my $result = $U->simplereq(
584         'open-ils.circ',
585         'open-ils.circ.checkin.override',
586         $self->{session}->{authtoken},
587         $params
588     );
589     if (ref($result) eq 'ARRAY') {
590         $result = $result->[0];
591     }
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());
599         my $data = {
600             ItemId => NCIP::Item::Id->new(
601                 {
602                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
603                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
604                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
605                 }
606             ),
607             UserId => NCIP::User::Id->new(
608                 {
609                     UserIdentifierType => 'Barcode Id',
610                     UserIdentifierValue => $circ_user->card->barcode()
611                 }
612             )
613         };
614
615         $response->data($data);
616
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.
621     } else {
622         $response->problem(_problem_from_event('Checkin Failed', $result));
623     }
624
625     return $response
626 }
627
628 =head2 renewitem
629
630     $response = $ils->renewitem($request);
631
632 Handle the RenewItem message.
633
634 =cut
635
636 sub renewitem {
637     my $self = shift;
638     my $request = shift;
639
640     # Check our session and login if necessary:
641     $self->login() unless ($self->checkauth());
642
643     # Common stuff:
644     my $message = $self->parse_request_type($request);
645     my $response = NCIP::Response->new({type => $message . 'Response'});
646     $response->header($self->make_header($request));
647
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);
652         return $response;
653     }
654
655     # Retrieve the copy details.
656     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
657     unless ($details) {
658         # Return an Unknown Item problem unless we find the copy.
659         $response->problem(
660             NCIP::Problem->new(
661                 {
662                     ProblemType => 'Unknown Item',
663                     ProblemDetail => "Item with barcode $item_barcode is not known.",
664                     ProblemElement => $item_idfield,
665                     ProblemValue => $item_barcode
666                 }
667             )
668         );
669         return $response;
670     }
671
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);
676         return $response;
677     }
678     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
679     if (ref($user) eq 'NCIP::Problem') {
680         $response->problem($user);
681         return $response;
682     }
683
684     # Isolate the copy.
685     my $copy = $details->{copy};
686
687     # Look for a circulation and examine its information:
688     my $circ = $details->{circ};
689
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
693     # location.
694     my $problem = $self->check_circ_details($circ, $copy, $user);
695     if ($problem) {
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);
702         }
703         $response->problem($problem);
704         return $response;
705     }
706
707     # Check if user is blocked from renewals:
708     $problem = $self->check_user_for_problems($user, 'RENEW');
709     if ($problem) {
710         # Replace the ProblemElement and ProblemValue fields.
711         $problem->ProblemElement($user_idfield);
712         $problem->ProblemValue($user_barcode);
713         $response->problem($problem);
714         return $response;
715     }
716
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(
722             'open-ils.pcrud',
723             'open-ils.pcrud.retrieve.crcd',
724             $self->{session}->{authtoken},
725             $rule
726         )->gather(1);
727     }
728     if ($rule->max_renewals() < 1) {
729         $response->problem(
730             NCIP::Problem->new(
731                 {
732                     ProblemType => 'Item Not Renewable',
733                     ProblemDetail => 'Item may not be renewed.',
734                     ProblemElement => $item_idfield,
735                     ProblemValue => $item_barcode
736                 }
737             )
738         );
739         return $response;
740     }
741
742     # Check if there are renewals remaining on the latest circ:
743     if ($circ->renewal_remaining() < 1) {
744         $response->problem(
745             NCIP::Problem->new(
746                 {
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
751                 }
752             )
753         );
754         return $response;
755     }
756
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
759     # details.
760     my $params = {
761         copy => $copy,
762         patron_id => $user->id(),
763         sip_renewal => 1
764     };
765     my $r = $U->simplereq(
766         'open-ils.circ',
767         'open-ils.circ.renew.override',
768         $self->{session}->{authtoken},
769         $params
770     )->gather(1);
771
772     # We only look at the first one, since more than one usually means
773     # failure.
774     if (ref($r) eq 'ARRAY') {
775         $r = $r->[0];
776     }
777     if ($r->{textcode} ne 'SUCCESS') {
778         $problem = _problem_from_event('Renewal Failed', $r);
779         $response->problem($problem);
780     } else {
781         my $data = {
782             ItemId => NCIP::Item::Id->new(
783                 {
784                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
785                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
786                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
787                 }
788             ),
789             UserId => NCIP::User::Id->new(
790                 {
791                     UserIdentifierType => 'Barcode Id',
792                     UserIdentifierValue => $user->card->barcode()
793                 }
794             )
795         };
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();
803
804         $response->data($data);
805     }
806
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.
811
812     return $response;
813 }
814
815 =head2 checkoutitem
816
817     $response = $ils->checkoutitem($request);
818
819 Handle the Checkoutitem message.
820
821 =cut
822
823 sub checkoutitem {
824     my $self = shift;
825     my $request = shift;
826
827     # Check our session and login if necessary:
828     $self->login() unless ($self->checkauth());
829
830     # Common stuff:
831     my $message = $self->parse_request_type($request);
832     my $response = NCIP::Response->new({type => $message . 'Response'});
833     $response->header($self->make_header($request));
834
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);
839         return $response;
840     }
841
842     # Retrieve the copy details.
843     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
844     unless ($details) {
845         # Return an Unknown Item problem unless we find the copy.
846         $response->problem(
847             NCIP::Problem->new(
848                 {
849                     ProblemType => 'Unknown Item',
850                     ProblemDetail => "Item with barcode $item_barcode is not known.",
851                     ProblemElement => $item_idfield,
852                     ProblemValue => $item_barcode
853                 }
854             )
855         );
856         return $response;
857     }
858
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);
863         return $response;
864     }
865     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
866     if (ref($user) eq 'NCIP::Problem') {
867         $response->problem($user);
868         return $response;
869     }
870
871     # Isolate the copy.
872     my $copy = $details->{copy};
873
874     # Check if the copy can circulate.
875     unless ($self->copy_can_circulate($copy)) {
876         $response->problem(
877             NCIP::Problem->new(
878                 {
879                     ProblemType => 'Item Does Not Circulate',
880                     ProblemDetail => "Item with barcode $item_barcode does not circulate.",
881                     ProblemElement => $item_idfield,
882                     ProblemValue => $item_barcode
883                 }
884             )
885         );
886         return $response;
887     }
888
889     # Look for a circulation and examine its information:
890     my $circ = $details->{circ};
891
892     # Check if the item is already checked out.
893     if ($circ && !$circ->checkin_time()) {
894         $response->problem(
895             NCIP::Problem->new(
896                 {
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
901                 }
902             )
903         );
904         return $response;
905     }
906
907     # Check if user is blocked from circulation:
908     my $problem = $self->check_user_for_problems($user, 'CIRC');
909     if ($problem) {
910         # Replace the ProblemElement and ProblemValue fields.
911         $problem->ProblemElement($user_idfield);
912         $problem->ProblemValue($user_barcode);
913         $response->problem($problem);
914         return $response;
915     }
916
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
919     # into details.
920     my $params = {
921         copy => $copy,
922         patron_id => $user->id(),
923     };
924     my $r = $U->simplereq(
925         'open-ils.circ',
926         'open-ils.circ.checkout.full.override',
927         $self->{session}->{authtoken},
928         $params
929     );
930
931     # We only look at the first one, since more than one usually means
932     # failure.
933     if (ref($r) eq 'ARRAY') {
934         $r = $r->[0];
935     }
936     if ($r->{textcode} ne 'SUCCESS') {
937         $problem = _problem_from_event('Check Out Failed', $r);
938         $response->problem($problem);
939     } else {
940         my $data = {
941             ItemId => NCIP::Item::Id->new(
942                 {
943                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
944                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
945                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
946                 }
947             ),
948             UserId => NCIP::User::Id->new(
949                 {
950                     UserIdentifierType => 'Barcode Id',
951                     UserIdentifierValue => $user->card->barcode()
952                 }
953             )
954         };
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();
962
963         $response->data($data);
964     }
965
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.
970
971     return $response;
972 }
973
974 =head2 requestitem
975
976     $response = $ils->requestitem($request);
977
978 Handle the NCIP RequestItem message.
979
980 =cut
981
982 sub requestitem {
983     my $self = shift;
984     my $request = shift;
985     # Check our session and login if necessary:
986     $self->login() unless ($self->checkauth());
987
988     # Common stuff:
989     my $message = $self->parse_request_type($request);
990     my $response = NCIP::Response->new({type => $message . 'Response'});
991     $response->header($self->make_header($request));
992
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);
1001         return $response;
1002     }
1003     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1004     if (ref($user) eq 'NCIP::Problem') {
1005         $response->problem($user);
1006         return $response;
1007     }
1008     my $problem = $self->check_user_for_problems($user, 'HOLD');
1009     if ($problem) {
1010         $response->problem($problem);
1011         return $response;
1012     }
1013
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.
1021
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.)
1025
1026     # This here is the thing we're going to put on hold:
1027     my $item;
1028
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.
1036             $response->problem(
1037                 NCIP::Problem->new(
1038                     {
1039                         ProblemType => 'Unknown Item',
1040                         ProblemDetail => "Item with barcode $item_barcode is not known.",
1041                         ProblemElement => $item_idfield,
1042                         ProblemValue => $item_barcode
1043                     }
1044                 )
1045             );
1046             return $response;
1047         }
1048         $item = $copy_details->{volume}; # We place a volume hold.
1049     }
1050
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.
1053     unless ($item) {
1054         my @biblio_ids = $self->find_bibliographic_ids($request);
1055         if (@biblio_ids) {
1056             $item = $self->find_target_via_bibliographic_id(@biblio_ids);
1057         }
1058     }
1059
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.
1062     unless ($item) {
1063         if (ref($item_barcode) eq 'NCIP::Problem') {
1064             $response->problem($item_barcode);
1065         } else {
1066             $response->problem(
1067                 NCIP::Problem->new(
1068                     {
1069                         ProblemType => 'Request Item Not Found',
1070                         ProblemDetail => 'Unable to determine the item to request from input message.',
1071                         ProblemElement => 'NULL',
1072                         ProblemValue => 'NULL'
1073                     }
1074                 )
1075             );
1076         }
1077         return $response;
1078     } elsif (ref($item) eq 'NCIP::Problem') {
1079         $response->problem($item);
1080         return $response;
1081     }
1082
1083     # See if we were given a PickupLocation.
1084     my $location;
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);
1090     }
1091
1092     # Look for a NeedBeforeDate to use as expiration...
1093     my $hold_expiration = $request->{$message}->{NeedBeforeDate};
1094
1095     # Place the hold.
1096     my $hold = $self->place_hold($item, $user, $location, $hold_expiration);
1097     if (ref($hold) eq 'NCIP::Problem') {
1098         $response->problem($hold);
1099     } else {
1100         my $data = {
1101             RequestId => NCIP::RequestId->new(
1102                 RequestIdentifierType => 'SYSNUMBER',
1103                 RequestIdentifierValue => $hold->id()
1104             ),
1105             UserId => NCIP::User::Id->new(
1106                 {
1107                     UserIdentifierType => 'Barcode Id',
1108                     UserIdentifierValue => $user->card->barcode()
1109                 }
1110             ),
1111             RequestType => $request->{$message}->{RequestType},
1112             RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1113         };
1114         $response->data($data);
1115     }
1116
1117     return $response;
1118 }
1119
1120 =head2 cancelrequestitem
1121
1122     $response = $ils->cancelrequestitem($request);
1123
1124 Handle the NCIP CancelRequestItem message.
1125
1126 =cut
1127
1128 sub cancelrequestitem {
1129     my $self = shift;
1130     my $request = shift;
1131     # Check our session and login if necessary:
1132     $self->login() unless ($self->checkauth());
1133
1134     # Common stuff:
1135     my $message = $self->parse_request_type($request);
1136     my $response = NCIP::Response->new({type => $message . 'Response'});
1137     $response->header($self->make_header($request));
1138
1139     # UserId is required by the standard, but we might not really need it.
1140     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1141     if (ref($user_barcode) eq 'NCIP::Problem') {
1142         $response->problem($user_barcode);
1143         return $response;
1144     }
1145     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1146     if (ref($user) eq 'NCIP::Problem') {
1147         $response->problem($user);
1148         return $response;
1149     }
1150
1151     # See if we got a ItemId and a barcode:
1152     my $copy_details;
1153     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1154     if (ref($item_barcode) ne 'NCIP::Problem') {
1155         # Retrieve the copy details.
1156         $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1157         unless ($copy_details) {
1158             # Return an Unknown Item problem unless we find the copy.
1159             $response->problem(
1160                 NCIP::Problem->new(
1161                     {
1162                         ProblemType => 'Unknown Item',
1163                         ProblemDetail => "Item with barcode $item_barcode is not known.",
1164                         ProblemElement => $item_idfield,
1165                         ProblemValue => $item_barcode
1166                     }
1167                 )
1168             );
1169             return $response;
1170         }
1171     }
1172
1173     # See if we got a RequestId:
1174     my $requestid;
1175     if ($request->{$message}->{RequestId}) {
1176         $requestid = NCIP::RequestId->new(
1177             {
1178                 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1179                 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1180                 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1181             }
1182         )
1183     }
1184
1185     # Just a note: In the below, we cannot rely on the hold or transit
1186     # fields of the copy_details, even if we have retrieved it. This
1187     # is because that hold and transit may not be the ones that we're
1188     # looking for, i.e. they could be for another patron, etc.
1189
1190     # See if we can find the hold:
1191     my $hold;
1192     if ($requestid) {
1193         $hold = $U->simplereq(
1194             'open-ils.pcrud',
1195             'open-ils.pcrud.retrieve.ahr',
1196             $self->{session}->{authtoken},
1197             $requestid->{RequestIdentifierValue},
1198             {flesh => 1, flesh_fields => {ahr => ['transit']}}
1199         );
1200         unless ($hold) {
1201             # Report a problem that we couldn't find a hold by that id.
1202             $response->problem(
1203                 NCIP::Problem->new(
1204                     {
1205                         ProblemType => 'Unknown Request',
1206                         ProblemDetail => 'No request with this identifier found',
1207                         ProblemElement => 'RequestIdentifierValue',
1208                         ProblemValue => $requestid->{RequestIdentifierValue}
1209                     }
1210                 )
1211             )
1212         } elsif ($hold->cancel_time()) {
1213             $response->problem(
1214                 NCIP::Problem->new(
1215                     {
1216                         ProblemType => 'Request Already Canceled',
1217                         ProblemDetail => 'Request has already been canceled',
1218                         ProblemElement => 'RequestIdentifierValue',
1219                         ProblemValue => $requestid->{RequestIdentifierValue}
1220                     }
1221                 )
1222             )
1223         } elsif ($hold->transit()) {
1224             $response->problem(
1225                 NCIP::Problem->new(
1226                     {
1227                         ProblemType => 'Request Already Processed',
1228                         ProblemDetail => 'Request has already been processed',
1229                         ProblemElement => 'RequestIdentifierValue',
1230                         ProblemValue => $requestid->{RequestIdentifierValue}
1231                     }
1232                 )
1233             )
1234         } elsif ($hold->usr() == $user->id()) {
1235             # Check the target matches the copy information, if any,
1236             # that we were given.
1237             my $obj_id;
1238             if ($copy_details) {
1239                 if ($hold->hold_type() eq 'V') {
1240                     $obj_id = $copy_details->{volume}->id();
1241                 } elsif ($hold->hold_type() eq 'T') {
1242                     $obj_id = $copy_details->{mvr}->doc_id();
1243                 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1244                     $obj_id = $copy_details->{copy}->id();
1245                 }
1246             }
1247             if ($obj_id && $hold->target() != $obj_id) {
1248                 $response->problem(
1249                     NCIP::Problem->new(
1250                         {
1251                             ProblemType => 'Request Not For This Item',
1252                             ProblemDetail => "Request is not for this item",
1253                             ProblemElement => $item_idfield,
1254                             ProblemElement => $item_barcode
1255                         }
1256                     )
1257                 )
1258             } else {
1259                 $self->cancel_hold($hold);
1260                 $response->data(
1261                     {
1262                         RequestId => $requestid,
1263                         UserId => NCIP::User::Id->new(
1264                             {
1265                                 UserIdentifierType => 'Barcode Id',
1266                                 UserIdentifierValue => $user->card->barcode()
1267                             }
1268                         )
1269                     }
1270                 )
1271             }
1272         } else {
1273             # Report a problem that the hold is not for this user.
1274             $response->problem(
1275                 NCIP::Problem->new(
1276                     {
1277                         ProblemType => 'Request Not For This User',
1278                         ProblemDetail => 'Request is not for this user.',
1279                         ProblemElement => $user_idfield,
1280                         ProblemValue => $user_barcode
1281                     }
1282                 )
1283             )
1284         }
1285     } else {
1286         # At this point, we *must have* an ItemId and therefore
1287         # $copy_details, so return the problem from looking up the
1288         # barcode if we don't have $copy_details.
1289         if (!$copy_details) {
1290             $response->problem($item_barcode);
1291         } else {
1292             # We have to search for the hold based on the copy details and
1293             # the user.  We'll need to search for copy (or force) holds, a
1294             # volume hold, or a title hold.
1295             $hold = $self->_hold_search($user, $copy_details);
1296             if ($hold && $hold->transit()) {
1297                 $response->problem(
1298                     NCIP::Problem->new(
1299                         {
1300                             ProblemType => 'Request Already Processed',
1301                             ProblemDetail => 'Request has already been processed',
1302                             ProblemElement => 'RequestIdentifierValue',
1303                             ProblemValue => $requestid->{RequestIdentifierValue}
1304                         }
1305                     )
1306                 )
1307             } elsif ($hold) {
1308                 $self->cancel_hold($hold);
1309                 $response->data(
1310                     {
1311                         RequestId => NCIP::RequestId->new(
1312                             {
1313                                 RequestIdentifierType => 'SYSNUMBER',
1314                                 RequestIdentifierValue => $hold->id()
1315                             }
1316                         ),
1317                         UserId => NCIP::User::Id->new(
1318                             {
1319                                 UserIdentifierType => 'Barcode Id',
1320                                 UserIdentifierValue => $user->card->barcode()
1321                             }
1322                         )
1323                     }
1324                 )
1325             } else {
1326                 $response->problem(
1327                     NCIP::Problem->new(
1328                         {
1329                             ProblemType => 'Unknown Request',
1330                             ProblemDetail => 'No request found for the item and user',
1331                             ProblemElement => 'NULL',
1332                             ProblemValue => 'NULL'
1333                         }
1334                     )
1335                 )
1336             }
1337         }
1338     }
1339
1340     return $response;
1341 }
1342
1343 =head1 METHODS USEFUL to SUBCLASSES
1344
1345 =head2 login
1346
1347     $ils->login();
1348
1349 Login to Evergreen via OpenSRF. It uses internal state from the
1350 configuration file to login.
1351
1352 =cut
1353
1354 # Login via OpenSRF to Evergreen.
1355 sub login {
1356     my $self = shift;
1357
1358     # Get the authentication seed.
1359     my $seed = $U->simplereq(
1360         'open-ils.auth',
1361         'open-ils.auth.authenticate.init',
1362         $self->{config}->{credentials}->{username}
1363     );
1364
1365     # Actually login.
1366     if ($seed) {
1367         my $response = $U->simplereq(
1368             'open-ils.auth',
1369             'open-ils.auth.authenticate.complete',
1370             {
1371                 username => $self->{config}->{credentials}->{username},
1372                 password => md5_hex(
1373                     $seed . md5_hex($self->{config}->{credentials}->{password})
1374                 ),
1375                 type => 'staff',
1376                 workstation => $self->{config}->{credentials}->{workstation}
1377             }
1378         );
1379         if ($response) {
1380             $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1381             $self->{session}->{authtime} = $response->{payload}->{authtime};
1382
1383             # Set/reset the work_ou and user data in case something changed.
1384
1385             # Retrieve the work_ou as an object.
1386             $self->{session}->{work_ou} = $U->simplereq(
1387                 'open-ils.pcrud',
1388                 'open-ils.pcrud.search.aou',
1389                 $self->{session}->{authtoken},
1390                 {shortname => $self->{config}->{credentials}->{work_ou}}
1391             );
1392
1393             # We need the user information in order to do some things.
1394             $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1395
1396         }
1397     }
1398 }
1399
1400 =head2 checkauth
1401
1402     $valid = $ils->checkauth();
1403
1404 Returns 1 if the object a 'valid' authtoken, 0 if not.
1405
1406 =cut
1407
1408 sub checkauth {
1409     my $self = shift;
1410
1411     # We use AppUtils to do the heavy lifting.
1412     if (defined($self->{session})) {
1413         if ($U->check_user_session($self->{session}->{authtoken})) {
1414             return 1;
1415         } else {
1416             return 0;
1417         }
1418     }
1419
1420     # If we reach here, we don't have a session, so we are definitely
1421     # not logged in.
1422     return 0;
1423 }
1424
1425 =head2 retrieve_user_by_barcode
1426
1427     $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1428
1429 Do a fleshed retrieve of a patron by barcode. Return the patron if
1430 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1431
1432 The id field argument is used for the ProblemElement field in the
1433 NCIP::Problem object.
1434
1435 An invalid patron is one where the barcode is not found in the
1436 database, the patron is deleted, or the barcode used to retrieve the
1437 patron is not active. The problem element is also returned if an error
1438 occurs during the retrieval.
1439
1440 =cut
1441
1442 sub retrieve_user_by_barcode {
1443     my ($self, $barcode, $idfield) = @_;
1444     my $result = $U->simplereq(
1445         'open-ils.actor',
1446         'open-ils.actor.user.fleshed.retrieve_by_barcode',
1447         $self->{session}->{authtoken},
1448         $barcode,
1449         1
1450     );
1451
1452     # Check for a failure, or a deleted, inactive, or expired user,
1453     # and if so, return empty userdata.
1454     if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1455             || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1456
1457         my $problem = NCIP::Problem->new();
1458         $problem->ProblemType('Unknown User');
1459         $problem->ProblemDetail("User with barcode $barcode unknown");
1460         $problem->ProblemElement($idfield);
1461         $problem->ProblemValue($barcode);
1462         $result = $problem;
1463     }
1464
1465     return $result;
1466 }
1467
1468 =head2 retrieve_user_by_id
1469
1470     $user = $ils->retrieve_user_by_id($id);
1471
1472 Similar to C<retrieve_user_by_barcode> but takes the user's database
1473 id rather than barcode. This is useful when you have a circulation or
1474 hold and need to get information about the user's involved in the hold
1475 or circulaiton.
1476
1477 It returns a fleshed user on success or undef on failure.
1478
1479 =cut
1480
1481 sub retrieve_user_by_id {
1482     my ($self, $id) = @_;
1483
1484     # Do a fleshed retrieve of the patron, and flesh the fields that
1485     # we would normally use.
1486     my $result = $U->simplereq(
1487         'open-ils.actor',
1488         'open-ils.actor.user.fleshed.retrieve',
1489         $self->{session}->{authtoken},
1490         $id,
1491         [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1492     );
1493     # Check for an error.
1494     undef($result) if ($result && $U->event_code($result));
1495
1496     return $result;
1497 }
1498
1499 =head2 check_user_for_problems
1500
1501     $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1502
1503 This function checks if a user has a blocked profile or any from a
1504 list of provided blocks. If it does, then a NCIP::Problem object is
1505 returned, otherwise an undefined value is returned.
1506
1507 The list of blocks appears as additional arguments after the user. You
1508 can provide any value(s) that might appear in a standing penalty block
1509 lit in Evergreen. The example above checks for HOLD, CIRC, and
1510 RENEW. Any number of such values can be provided. If none are
1511 provided, the function only checks if the patron's profiles appears in
1512 the object's blocked profiles list.
1513
1514 It stops on the first matching block, if any.
1515
1516 =cut
1517
1518 sub check_user_for_problems {
1519     my $self = shift;
1520     my $user = shift;
1521     my @blocks = @_;
1522
1523     # Fill this in if we have a problem, otherwise just return it.
1524     my $problem;
1525
1526     # First, check the user's profile.
1527     if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1528         $problem = NCIP::Problem->new(
1529             {
1530                 ProblemType => 'User Blocked',
1531                 ProblemDetail => 'User blocked from inter-library loan',
1532                 ProblemElement => 'NULL',
1533                 ProblemValue => 'NULL'
1534             }
1535         );
1536     }
1537
1538     # Next, check if the patron has one of the indicated blocks.
1539     unless ($problem) {
1540         foreach my $block (@blocks) {
1541             if (grep {$_->standing_penalty->block_list() =~ /$block/} @{$user->standing_penalties()}) {
1542                 $problem = NCIP::Problem->new(
1543                     {
1544                         ProblemType => 'User Blocked',
1545                         ProblemDetail => 'User blocked from ' .
1546                             ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1547                                                                 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1548                         ProblemElement => 'NULL',
1549                         ProblemValue => 'NULL'
1550                     }
1551                 );
1552                 last;
1553             }
1554         }
1555     }
1556
1557     return $problem;
1558 }
1559
1560 =head2 check_circ_details
1561
1562     $problem = $ils->check_circ_details($circ, $copy, $user);
1563
1564 Checks if we can checkin or renew a circulation. That is, the
1565 circulation is still open (i.e. the copy is still checked out), if we
1566 either own the copy or are the circulation location, and if the
1567 circulation is for the optional $user argument. $circ and $copy are
1568 required. $user is optional.
1569
1570 Returns a problem if any of the above conditions fail. Returns undef
1571 if they pass and we can proceed with the checkin or renewal.
1572
1573 If the failure occurred on the copy-related checks, then the
1574 ProblemElement field will be undefined and needs to be filled in with
1575 the item id field name. If the check for the copy being checked out to
1576 the provided user fails, then both ProblemElement and ProblemValue
1577 fields will be empty and need to be filled in by the caller.
1578
1579 =cut
1580
1581 sub check_circ_details {
1582     my ($self, $circ, $copy, $user) = @_;
1583
1584     # Shortcut for the next check.
1585     my $ou_id = $self->{session}->{work_ou}->id();
1586
1587     if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1588         # Item isn't checked out.
1589         return NCIP::Problem->new(
1590             {
1591                 ProblemType => 'Item Not Checked Out',
1592                 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1593                 ProblemValue => $copy->barcode()
1594             }
1595         );
1596     } else {
1597         # Get data on the patron who has it checked out.
1598         my $circ_user = $self->retrieve_user_by_id($circ->usr());
1599         if ($user && $circ_user && $user->id() != $circ_user->id()) {
1600             # The ProblemElement and ProblemValue field need to be
1601             # filled in by the caller.
1602             return NCIP::Problem->new(
1603                 {
1604                     ProblemType => 'Item Not Checked Out To This User',
1605                     ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1606                 }
1607             );
1608         }
1609     }
1610     # If we get here, we're good to go.
1611     return undef;
1612 }
1613
1614 =head2 retrieve_copy_details_by_barcode
1615
1616     $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1617
1618 Look up and retrieve some copy details by the copy barcode. This
1619 method returns either a hashref with the copy details or undefined if
1620 no copy exists with that barcode or if some error occurs.
1621
1622 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1623
1624 This method differs from C<retrieve_user_by_barcode> in that a copy
1625 cannot be invalid if it exists and it is not always an error if no
1626 copy exists. In some cases, when handling AcceptItem, we might prefer
1627 there to be no copy.
1628
1629 =cut
1630
1631 sub retrieve_copy_details_by_barcode {
1632     my $self = shift;
1633     my $barcode = shift;
1634
1635     my $copy = $U->simplereq(
1636         'open-ils.circ',
1637         'open-ils.circ.copy_details.retrieve.barcode',
1638         $self->{session}->{authtoken},
1639         $barcode
1640     );
1641
1642     # If $copy is an event, return undefined.
1643     if ($copy && $U->event_code($copy)) {
1644         undef($copy);
1645     }
1646
1647     return $copy;
1648 }
1649
1650 =head2 retrieve_org_unit_by_shortname
1651
1652     $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1653
1654 Retrieves an org. unit from the database by shortname. Returns the
1655 org. unit as a Fieldmapper object or undefined.
1656
1657 =cut
1658
1659 sub retrieve_org_unit_by_shortname {
1660     my $self = shift;
1661     my $shortname = shift;
1662
1663     my $aou = $U->simplereq(
1664         'open-ils.actor',
1665         'open-ils.actor.org_unit.retrieve_by_shortname',
1666         $shortname
1667     );
1668
1669     return $aou;
1670 }
1671
1672 =head2 retrieve_copy_location
1673
1674     $location = $ils->retrieve_copy_location($location_id);
1675
1676 Retrieve a copy location based on id.
1677
1678 =cut
1679
1680 sub retrieve_copy_location {
1681     my $self = shift;
1682     my $id = shift;
1683
1684     my $location = $U->simplereq(
1685         'open-ils.pcrud',
1686         'open-ils.pcrud.retrieve.acpl',
1687         $self->{session}->{authtoken},
1688         $id
1689     );
1690
1691     return $location;
1692 }
1693
1694 =head2 retrieve_biblio_record_entry
1695
1696     $bre = $ils->retrieve_biblio_record_entry($bre_id);
1697
1698 Given a biblio.record_entry.id, this method retrieves a bre object.
1699
1700 =cut
1701
1702 sub retrieve_biblio_record_entry {
1703     my $self = shift;
1704     my $id = shift;
1705
1706     my $bre = $U->simplereq(
1707         'open-ils.pcrud',
1708         'open-ils.pcrud.retrieve.bre',
1709         $self->{session}->{authtoken},
1710         $id
1711     );
1712
1713     return $bre;
1714 }
1715
1716 =head2 create_precat_copy
1717
1718     $item_info->{
1719         barcode => '312340123456789',
1720         author => 'Public, John Q.',
1721         title => 'Magnum Opus',
1722         call_number => '005.82',
1723         publisher => 'Brick House',
1724         publication_date => '2014'
1725     };
1726
1727     $item = $ils->create_precat_copy($item_info);
1728
1729
1730 Create a "precat" copy to use for the incoming item using a hashref of
1731 item information. At a minimum, the barcode, author and title fields
1732 need to be filled in. The other fields are ignored if provided.
1733
1734 This method is called by the AcceptItem handler if the C<use_precats>
1735 configuration option is turned on.
1736
1737 =cut
1738
1739 sub create_precat_copy {
1740     my $self = shift;
1741     my $item_info = shift;
1742
1743     my $item = Fieldmapper::asset::copy->new();
1744     $item->barcode($item_info->{barcode});
1745     $item->call_number(OILS_PRECAT_CALL_NUMBER);
1746     $item->dummy_title($item_info->{title});
1747     $item->dummy_author($item_info->{author});
1748     $item->circ_lib($self->{session}->{work_ou}->id());
1749     $item->circulate('t');
1750     $item->holdable('t');
1751     $item->opac_visible('f');
1752     $item->deleted('f');
1753     $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1754     $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1755     $item->location(1);
1756     $item->status(0);
1757     $item->editor($self->{session}->{user}->id());
1758     $item->creator($self->{session}->{user}->id());
1759     $item->isnew(1);
1760
1761     # Actually create it:
1762     my $xact;
1763     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1764     $ses->connect();
1765     eval {
1766         $xact = $ses->request(
1767             'open-ils.pcrud.transaction.begin',
1768             $self->{session}->{authtoken}
1769         )->gather(1);
1770         $item = $ses->request(
1771             'open-ils.pcrud.create.acp',
1772             $self->{session}->{authtoken},
1773             $item
1774         )->gather(1);
1775         $xact = $ses->request(
1776             'open-ils.pcrud.transaction.commit',
1777             $self->{session}->{authtoken}
1778         )->gather(1);
1779     };
1780     if ($@) {
1781         undef($item);
1782         if ($xact) {
1783             eval {
1784                 $ses->request(
1785                     'open-ils.pcrud.transaction.rollback',
1786                     $self->{session}->{authtoken}
1787                 )->gather(1);
1788             };
1789         }
1790     }
1791     $ses->disconnect();
1792
1793     return $item;
1794 }
1795
1796 =head2 create_fuller_copy
1797
1798     $item_info->{
1799         barcode => '31234003456789',
1800         author => 'Public, John Q.',
1801         title => 'Magnum Opus',
1802         call_number => '005.82',
1803         publisher => 'Brick House',
1804         publication_date => '2014'
1805     };
1806
1807     $item = $ils->create_fuller_copy($item_info);
1808
1809 Creates a skeletal bibliographic record, call number, and copy for the
1810 incoming item using a hashref with item information in it. At a
1811 minimum, the barcode, author, title, and call_number fields must be
1812 filled in.
1813
1814 This method is used by the AcceptItem handler if the C<use_precats>
1815 configuration option is NOT set.
1816
1817 =cut
1818
1819 sub create_fuller_copy {
1820     my $self = shift;
1821     my $item_info = shift;
1822
1823     my $item;
1824
1825     # We do everything in one transaction, because it should be atomic.
1826     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1827     $ses->connect();
1828     my $xact;
1829     eval {
1830         $xact = $ses->request(
1831             'open-ils.pcrud.transaction.begin',
1832             $self->{session}->{authtoken}
1833         )->gather(1);
1834     };
1835     if ($@) {
1836         undef($xact);
1837     }
1838
1839     # The rest depends on there being a transaction.
1840     if ($xact) {
1841
1842         # Create the MARC record.
1843         my $record = MARC::Record->new();
1844         $record->encoding('UTF-8');
1845         $record->leader('00881nam a2200193   4500');
1846         my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
1847         my @fields = ();
1848         push(@fields, MARC::Field->new('005', $datespec));
1849         push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
1850         push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
1851         # Publisher is a little trickier:
1852         if ($item_info->{publisher}) {
1853             my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
1854             $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
1855             push(@fields, $pub);
1856         }
1857         # We have no idea if the author is personal corporate or something else, so we use a 720.
1858         push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
1859         $record->append_fields(@fields);
1860         my $marc = clean_marc($record);
1861
1862         # Create the bib object.
1863         my $bib = Fieldmapper::biblio::record_entry->new();
1864         $bib->creator($self->{session}->{user}->id());
1865         $bib->editor($self->{session}->{user}->id());
1866         $bib->source($self->{bib_source}->id());
1867         $bib->active('t');
1868         $bib->deleted('f');
1869         $bib->marc($marc);
1870         $bib->isnew(1);
1871
1872         eval {
1873             $bib = $ses->request(
1874                 'open-ils.pcrud.create.bre',
1875                 $self->{session}->{authtoken},
1876                 $bib
1877             )->gather(1);
1878         };
1879         if ($@) {
1880             undef($bib);
1881             eval {
1882                 $ses->request(
1883                     'open-ils.pcrud.transaction.rollback',
1884                     $self->{session}->{authtoken}
1885                 )->gather(1);
1886             };
1887         }
1888
1889         # Create the call number
1890         my $acn;
1891         if ($bib) {
1892             $acn = Fieldmapper::asset::call_number->new();
1893             $acn->creator($self->{session}->{user}->id());
1894             $acn->editor($self->{session}->{user}->id());
1895             $acn->label($item_info->{call_number});
1896             $acn->record($bib->id());
1897             $acn->owning_lib($self->{session}->{work_ou}->id());
1898             $acn->deleted('f');
1899             $acn->isnew(1);
1900
1901             eval {
1902                 $acn = $ses->request(
1903                     'open-ils.pcrud.create.acn',
1904                     $self->{session}->{authtoken},
1905                     $acn
1906                 )->gather(1);
1907             };
1908             if ($@) {
1909                 undef($acn);
1910                 eval {
1911                     $ses->request(
1912                         'open-ils.pcrud.transaction.rollback',
1913                         $self->{session}->{authtoken}
1914                     )->gather(1);
1915                 };
1916             }
1917         }
1918
1919         # create the copy
1920         if ($acn) {
1921             $item = Fieldmapper::asset::copy->new();
1922             $item->barcode($item_info->{barcode});
1923             $item->call_number($acn->id());
1924             $item->circ_lib($self->{session}->{work_ou}->id);
1925             $item->circulate('t');
1926             if ($self->{config}->{items}->{use_force_holds}) {
1927                 $item->holdable('f');
1928             } else {
1929                 $item->holdable('t');
1930             }
1931             $item->opac_visible('f');
1932             $item->deleted('f');
1933             $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1934             $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1935             $item->location(1);
1936             $item->status(0);
1937             $item->editor($self->{session}->{user}->id);
1938             $item->creator($self->{session}->{user}->id);
1939             $item->isnew(1);
1940
1941             eval {
1942                 $item = $ses->request(
1943                     'open-ils.pcrud.create.acp',
1944                     $self->{session}->{authtoken},
1945                     $item
1946                 )->gather(1);
1947
1948                 # Cross our fingers and commit the work.
1949                 $xact = $ses->request(
1950                     'open-ils.pcrud.transaction.commit',
1951                     $self->{session}->{authtoken}
1952                 )->gather(1);
1953             };
1954             if ($@) {
1955                 undef($item);
1956                 eval {
1957                     $ses->request(
1958                         'open-ils.pcrud.transaction.rollback',
1959                         $self->{session}->{authtoken}
1960                     )->gather(1) if ($xact);
1961                 };
1962             }
1963         }
1964     }
1965
1966     # We need to disconnect our session.
1967     $ses->disconnect();
1968
1969     # Now, we handle our asset stat_cat entries.
1970     if ($item) {
1971         # It would be nice to do these in the above transaction, but
1972         # pcrud does not support the ascecm object, yet.
1973         foreach my $entry (@{$self->{stat_cat_entries}}) {
1974             my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1975             $map->isnew(1);
1976             $map->stat_cat($entry->stat_cat());
1977             $map->stat_cat_entry($entry->id());
1978             $map->owning_copy($item->id());
1979             # We don't really worry if it succeeds or not.
1980             $U->simplereq(
1981                 'open-ils.circ',
1982                 'open-ils.circ.stat_cat.asset.copy_map.create',
1983                 $self->{session}->{authtoken},
1984                 $map
1985             );
1986         }
1987     }
1988
1989     return $item;
1990 }
1991
1992 =head2 place_hold
1993
1994     $hold = $ils->place_hold($item, $user, $location, $expiration);
1995
1996 This function places a hold on $item for $user for pickup at
1997 $location. If location is not provided or undefined, the user's home
1998 library is used as a fallback.
1999
2000 The $expiration argument is optional and must be a properly formatted
2001 ISO date time. It will be used as the hold expire time, if
2002 provided. Otherwise the system default time will be used.
2003
2004 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2005 (biblio::record_entry). The appropriate hold type will be placed
2006 depending on the object.
2007
2008 On success, the method returns the object representing the hold. On
2009 failure, a NCIP::Problem object, describing the failure, is returned.
2010
2011 =cut
2012
2013 sub place_hold {
2014     my $self = shift;
2015     my $item = shift;
2016     my $user = shift;
2017     my $location = shift;
2018     my $expiration = shift;
2019
2020     # If $location is undefined, use the user's home_ou, which should
2021     # have been fleshed when the user was retrieved.
2022     $location = $user->home_ou() unless ($location);
2023
2024     # $hold is the hold. $params is for the is_possible check.
2025     my ($hold, $params);
2026
2027     # Prep the hold with fields common to all hold types:
2028     $hold = Fieldmapper::action::hold_request->new();
2029     $hold->isnew(1); # Just to make sure.
2030     $hold->target($item->id());
2031     $hold->usr($user->id());
2032     $hold->pickup_lib($location->id());
2033     $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2034     if (!$user->email()) {
2035         $hold->email_notify('f');
2036         $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2037     } else {
2038         $hold->email_notify('t');
2039     }
2040
2041     # Ditto the params:
2042     $params = { pickup_lib => $location->id(), patronid => $user->id() };
2043
2044     if (ref($item) eq 'Fieldmapper::asset::copy') {
2045         my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2046         $hold->hold_type($type);
2047         $hold->current_copy($item->id());
2048         $params->{hold_type} = $type;
2049         $params->{copy_id} = $item->id();
2050     } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2051         $hold->hold_type('V');
2052         $params->{hold_type} = 'V';
2053         $params->{volume_id} = $item->id();
2054     } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2055         $hold->hold_type('T');
2056         $params->{hold_type} = 'T';
2057         $params->{titleid} = $item->id();
2058     }
2059
2060     # Check for a duplicate hold:
2061     my $duplicate = $U->simplereq(
2062         'open-ils.pcrud',
2063         'open-ils.pcrud.search.ahr',
2064         $self->{session}->{authtoken},
2065         {
2066             hold_type => $hold->hold_type(),
2067             target => $hold->target(),
2068             usr => $hold->usr(),
2069             expire_time => {'>' => 'now'},
2070             cancel_time => undef,
2071             fulfillment_time => undef
2072         }
2073     );
2074     if ($duplicate) {
2075         return NCIP::Problem->new(
2076             {
2077                 ProblemType => 'Duplicate Request',
2078                 ProblemDetail => 'A request for this item already exists for this patron.',
2079                 ProblemElement => 'NULL',
2080                 ProblemValue => 'NULL'
2081             }
2082         );
2083     }
2084
2085     # Check if the hold is possible:
2086     my $r = $U->simplereq(
2087         'open-ils.circ',
2088         'open-ils.circ.title_hold.is_possible',
2089         $self->{session}->{authtoken},
2090         $params
2091     );
2092
2093     if ($r->{success}) {
2094         $hold = $U->simplereq(
2095             'open-ils.circ',
2096             'open-ils.circ.holds.create.override',
2097             $self->{session}->{authtoken},
2098             $hold
2099         );
2100         if (ref($hold) eq 'HASH') {
2101             $hold = _problem_from_event('Request Not Possible', $hold);
2102         }
2103     } elsif ($r->{last_event}) {
2104         $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2105     } elsif ($r->{textcode}) {
2106         $hold = _problem_from_event('Request Not Possible', $r);
2107     } else {
2108         $hold = _problem_from_event('Request Not Possible');
2109     }
2110
2111     return $hold;
2112 }
2113
2114 =head2 cancel_hold
2115
2116     $ils->cancel_hold($hold);
2117
2118 This method cancels the hold argument. It makes no checks on the hold,
2119 so if there are certain conditions that need to be fulfilled before
2120 the hold is canceled, then you must check them before calling this
2121 method.
2122
2123 It returns undef on success or failure. If it fails, you've usually
2124 got bigger problems.
2125
2126 =cut
2127
2128 sub cancel_hold {
2129     my $self = shift;
2130     my $hold = shift;
2131
2132     my $r = $U->simplereq(
2133         'open-ils.circ',
2134         'open-ils.circ.hold.cancel',
2135         $self->{session}->{authtoken},
2136         $hold->id(),
2137         '5',
2138         'Canceled via NCIPServer'
2139     );
2140
2141     return undef;
2142 }
2143
2144 =head2 delete_copy
2145
2146     $ils->delete_copy($copy);
2147
2148 Deletes the copy, and if it is owned by our work_ou and not a precat,
2149 we also delete the volume and bib on which the copy depends.
2150
2151 =cut
2152
2153 sub delete_copy {
2154     my $self = shift;
2155     my $copy = shift;
2156
2157     # Shortcut for ownership checks below.
2158     my $ou_id = $self->{session}->{work_ou}->id();
2159
2160     # First, make sure the copy is not already deleted and we own it.
2161     return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2162
2163     # Indicate we want to delete the copy.
2164     $copy->isdeleted(1);
2165
2166     # Delete the copy using a backend call that will delete the copy,
2167     # the call number, and bib when appropriate.
2168     my $result = $U->simplereq(
2169         'open-ils.cat',
2170         'open-ils.cat.asset.copy.fleshed.batch.update.override',
2171         $self->{session}->{authtoken},
2172         [$copy]
2173     );
2174
2175     # We are currently not checking for succes or failure of the
2176     # above. At some point, someone may want to.
2177
2178     return undef;
2179 }
2180
2181 =head2 copy_can_circulate
2182
2183     $can_circulate = $ils->copy_can_circulate($copy);
2184
2185 Check if the copy's location and the copy itself allow
2186 circulation. Return true if they do, and false if they do not.
2187
2188 =cut
2189
2190 sub copy_can_circulate {
2191     my $self = shift;
2192     my $copy = shift;
2193
2194     my $location = $copy->location();
2195     unless (ref($location)) {
2196         $location = $self->retrieve_copy_location($location);
2197     }
2198
2199     return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2200 }
2201
2202 =head2 copy_can_fulfill
2203
2204     $can_fulfill = $ils->copy_can_fulfill($copy);
2205
2206 Check if the copy's location and the copy itself allow
2207 holds. Return true if they do, and false if they do not.
2208
2209 =cut
2210
2211 sub copy_can_fulfill {
2212     my $self = shift;
2213     my $copy = shift;
2214
2215     my $location = $copy->location();
2216     unless (ref($location)) {
2217         $location = $self->retrieve_copy_location($location);
2218     }
2219
2220     return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2221 }
2222
2223 =head1 OVERRIDDEN PARENT METHODS
2224
2225 =head2 find_user_barcode
2226
2227 We dangerously override our parent's C<find_user_barcode> to return
2228 either the $barcode or a Problem object. In list context the barcode
2229 or problem will be the first argument and the id field, if any, will
2230 be the second. We also add a second, optional, argument to indicate a
2231 default value for the id field in the event of a failure to find
2232 anything at all. (Perl lets us get away with this.)
2233
2234 =cut
2235
2236 sub find_user_barcode {
2237     my $self = shift;
2238     my $request = shift;
2239     my $default = shift;
2240
2241     unless ($default) {
2242         my $message = $self->parse_request_type($request);
2243         if ($message eq 'LookupUser') {
2244             $default = 'AuthenticationInputData';
2245         } else {
2246             $default = 'UserIdentifierValue';
2247         }
2248     }
2249
2250     my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2251
2252     unless ($value) {
2253         $idfield = $default unless ($idfield);
2254         $value = NCIP::Problem->new();
2255         $value->ProblemType('Needed Data Missing');
2256         $value->ProblemDetail('Cannot find user barcode in message.');
2257         $value->ProblemElement($idfield);
2258         $value->ProblemValue('NULL');
2259     }
2260
2261     return (wantarray) ? ($value, $idfield) : $value;
2262 }
2263
2264 =head2 find_item_barcode
2265
2266 We do pretty much the same thing as with C<find_user_barcode> for
2267 C<find_item_barcode>.
2268
2269 =cut
2270
2271 sub find_item_barcode {
2272     my $self = shift;
2273     my $request = shift;
2274     my $default = shift || 'ItemIdentifierValue';
2275
2276     my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2277
2278     unless ($value) {
2279         $idfield = $default unless ($idfield);
2280         $value = NCIP::Problem->new();
2281         $value->ProblemType('Needed Data Missing');
2282         $value->ProblemDetail('Cannot find item barcode in message.');
2283         $value->ProblemElement($idfield);
2284         $value->ProblemValue('NULL');
2285     }
2286
2287     return (wantarray) ? ($value, $idfield) : $value;
2288 }
2289
2290 =head2 find_target_via_bibliographic_id
2291
2292     $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2293
2294 Searches for a bibliographic record to put on hold and returns an
2295 appropriate hold target item depending upon what it finds. If an
2296 appropriate, single target cannot be found, it returns an
2297 NCIP::Problem with the problem message.
2298
2299 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2300 identifiers. If nothing is found, this method can return undef. (Gotta
2301 love Perl and untyped/weakly typed languages in general!)
2302
2303 TODO: Figure out how to search OCLC numbers. We probably need to use
2304 "MARC Expert Search" if we don't want to do a JSON query on
2305 metabib.full_rec.
2306
2307 =cut
2308
2309 sub find_target_via_bibliographid_id {
2310     my $self = shift;
2311     my @biblio_ids = @_;
2312
2313     # The item that we find:
2314     my $item;
2315
2316     # Id for our bib in Evergreen:
2317     my $bibid;
2318
2319     # First, let's look for a SYSNUMBER:
2320     my ($idobj) = grep
2321         { $_->{BibligraphicRecordIdentifierCode} eq 'SYSNUMBER' || $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER'
2322               || $_->{AgencyId} }
2323             @biblio_ids;
2324     if ($idobj) {
2325         my $loc;
2326         # BibliographicRecordId can have an AgencyId field if the
2327         # BibliographicRecordIdentifierCode is absent.
2328         if ($idobj->{AgencyId}) {
2329             $bibid = $idobj->{BibliographicRecordIdentifier};
2330             my $locname = $idobj->{AgencyId};
2331             if ($locname) {
2332                 $locname =~ s/.*://;
2333                 $loc = $self->retrieve_org_unit_by_shortname($locname);
2334             }
2335         } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2336             $bibid = $idobj->{BibliographicRecordIdentifierCode}
2337         } else {
2338             $bibid = $idobj->{BibliographicItemIdentifierCode}
2339         }
2340         if ($bibid && $loc) {
2341             $item = $self->_call_number_search($bibid, $loc);
2342         } else {
2343             $item = $U->simplereq(
2344                 'open-ils.pcrud',
2345                 'open-ils.pcrud.retrieve.bre',
2346                 $self->{session}->{authtoken},
2347                 $bibid
2348             );
2349         }
2350         # Check if item is deleted so we'll look for more
2351         # possibilties.
2352         undef($item) if ($item && $U->is_true($item->deleted()));
2353     }
2354
2355     # Build an array of id objects based on the other identifier fields.
2356     my @idobjs = grep
2357         {
2358             $_->{BibliographicRecordIdentifierCode} eq 'ISBN' || $_->{BibliographicItemIdentifierCode} eq 'ISBN'
2359             ||
2360             $_->{BibliographicRecordIdentifierCode} eq 'ISSN' || $_->{BibliographicItemIdentifierCode} eq 'ISSN'
2361         } @biblio_ids;
2362
2363     if (@idobjs) {
2364         my $stashed_problem;
2365         # Reuse $idobj from above.
2366         foreach $idobj (@idobjs) {
2367             my ($idvalue, $idtype, $idfield);
2368             if ($_->{BibliographicItemIdentifier}) {
2369                 $idvalue = $_->{BibliographicItemIdentifier};
2370                 $idtype = $_->{BibliographicItemIdentifierCode};
2371                 $idfield = 'BibliographicItemIdentifier';
2372             } else {
2373                 $idvalue = $_->{BibliographicRecordIdentifier};
2374                 $idtype = $_->{BibliographicRecordIdentifierCode};
2375                 $idfield = 'BibliographicRecordIdentifier';
2376             }
2377             $item = $self->_bib_search($idvalue, $idtype);
2378             if (ref($item) eq 'NCIP::Problem') {
2379                 $stashed_problem = $item unless($stashed_problem);
2380                 $stashed_problem->ProblemElement($idfield);
2381                 undef($item);
2382             }
2383             last if ($item);
2384         }
2385         $item = $stashed_problem if (!$item && $stashed_problem);
2386     }
2387
2388     return $item;
2389 }
2390
2391 # private subroutines not meant to be used directly by subclasses.
2392 # Most have to do with setup and/or state checking of implementation
2393 # components.
2394
2395 # Find, load, and parse our configuration file:
2396 sub _configure {
2397     my $self = shift;
2398
2399     # Find the configuration file via variables:
2400     my $file = OILS_NCIP_CONFIG_DEFAULT;
2401     $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2402
2403     $self->{config} = XMLin($file, NormaliseSpace => 2,
2404                             ForceArray => ['block_profile', 'stat_cat_entry']);
2405 }
2406
2407 # Bootstrap OpenSRF::System and load the IDL.
2408 sub _bootstrap {
2409     my $self = shift;
2410
2411     my $bootstrap_config = $self->{config}->{bootstrap};
2412     OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2413
2414     my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2415     Fieldmapper->import(IDL => $idl);
2416 }
2417
2418 # Login and then initialize some object data based on the
2419 # configuration.
2420 sub _init {
2421     my $self = shift;
2422
2423     # Login to Evergreen.
2424     $self->login();
2425
2426     # Load the barred groups as pgt objects into a blocked_profiles
2427     # list.
2428     $self->{blocked_profiles} = [];
2429     foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2430         my $pgt;
2431         if (ref $_) {
2432             $pgt = $U->simplereq(
2433                 'open-ils.pcrud',
2434                 'open-ils.pcrud.retrieve.pgt',
2435                 $self->{session}->{authtoken},
2436                 $_->{grp}
2437             );
2438         } else {
2439             $pgt = $U->simplereq(
2440                 'open-ils.pcrud',
2441                 'open-ils.pcrud.search.pgt',
2442                 $self->{session}->{authtoken},
2443                 {name => $_}
2444             );
2445         }
2446         push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2447     }
2448
2449     # Load the bib source if we're not using precats.
2450     unless ($self->{config}->{items}->{use_precats}) {
2451         # Retrieve the default
2452         $self->{bib_source} = $U->simplereq(
2453             'open-ils.pcrud',
2454             'open-ils.pcrud.retrieve.cbs',
2455             $self->{session}->{authtoken},
2456             BIB_SOURCE_DEFAULT);
2457         my $data = $self->{config}->{items}->{bib_source};
2458         if ($data) {
2459             $data = $data->[0] if (ref($data) eq 'ARRAY');
2460             my $result;
2461             if (ref $data) {
2462                 $result = $U->simplereq(
2463                     'open-ils.pcrud',
2464                     'open-ils.pcrud.retrieve.cbs',
2465                     $self->{session}->{authtoken},
2466                     $data->{cbs}
2467                 );
2468             } else {
2469                 $result = $U->simplereq(
2470                     'open-ils.pcrud',
2471                     'open-ils.pcrud.search.cbs',
2472                     $self->{session}->{authtoken},
2473                     {source => $data}
2474                 );
2475             }
2476             $self->{bib_source} = $result if ($result);
2477         }
2478     }
2479
2480     # Load the required asset.stat_cat_entries:
2481     $self->{stat_cat_entries} = [];
2482     # First, make a regex for our ou and ancestors:
2483     my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2484     my $re = qr/(?:$ancestors)/;
2485     # Get the uniq stat_cat ids from the configuration:
2486     my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2487     # Retrieve all of the fleshed stat_cats and entries for the above.
2488     my $stat_cats = $U->simplereq(
2489         'open-ils.circ',
2490         'open-ils.circ.stat_cat.asset.retrieve.batch',
2491         $self->{session}->{authtoken},
2492         @cats
2493     );
2494     foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2495         # Must have the stat_cat attr and the name, so we must have a
2496         # reference.
2497         next unless(ref $entry);
2498         my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2499         push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2500     }
2501 }
2502
2503 # Search asset.call_number by a bre.id and location object. Return the
2504 # "closest" call_number if found, undef otherwise.
2505 sub _call_number_search {
2506     my $self = shift;
2507     my $bibid = shift;
2508     my $location = shift;
2509
2510     # At some point, this should be smarter, and we should retrieve
2511     # ancestors and descendants and search with a JSON query or some
2512     # such with results ordered by proximity to the original location,
2513     # but I don't have time to implement that right now.
2514     my $acn = $U->simplereq(
2515         'open-ils.prcud',
2516         'open-ils.pcrud.search.acn',
2517         $self->{session}->{authtoken},
2518         {record => $bibid, owning_lib => $location->id()}
2519     );
2520
2521     return $acn;
2522 }
2523
2524 # Do a multiclass.query to search for items by isbn or issn.
2525 sub _bib_search {
2526     my $self = shift;
2527     my $idvalue = shift;
2528     my $idtype = shift;
2529     my $item;
2530
2531     my $result = $U->simplereq(
2532         'open-ils.search',
2533         'open-ils.search.biblio.multiclass',
2534         {searches => {lc($idtype) => $idvalue}}
2535     );
2536
2537     if ($result && $result->{count}) {
2538         if ($result->{count} > 1) {
2539             $item = NCIP::Problem->new(
2540                 {
2541                     ProblemType => 'Non-Unique Item',
2542                     ProblemDetail => 'More than one item matches the request.',
2543                     ProblemElement => '',
2544                     ProblemValue => $idvalue
2545                 }
2546             );
2547         }
2548         my $bibid = $result->{ids}->[0]->[0];
2549         $item = $U->simplereq(
2550             'open-ils.pcrud',
2551             'open-ils.pcrud.retrieve.bre',
2552             $self->{session}->{authtoken},
2553             $bibid
2554         );
2555     }
2556
2557     return $item;
2558 }
2559
2560 # Search for holds using the user and copy_details information:
2561 sub _hold_search {
2562     my $self = shift;
2563     my $user = shift;
2564     my $copy_details = shift;
2565
2566     my $hold;
2567
2568     # Retrieve all of the user's active holds, and then search them in Perl.
2569     my $holds_list = $U->simplereq(
2570         'open-ils.circ',
2571         'open-ils.circ.holds.retrieve',
2572         $self->{session}->{authtoken},
2573         $user->id(),
2574         0
2575     );
2576
2577     if ($holds_list && @$holds_list) {
2578         my @holds;
2579         # Look for title holds (the most common), first:
2580         my $targetid = $copy_details->{mvr}->doc_id();
2581         @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2582         unless (@holds) {
2583             # Look for volume holds, the next most common:
2584             $targetid = $copy_details->{volume}->id();
2585             @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2586         }
2587         unless (@holds) {
2588             # Look for copy and force holds, the least likely.
2589             $targetid = $copy_details->{copy}->id();
2590             @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
2591         }
2592         # There should only be 1, at this point, if there are any.
2593         if (@holds) {
2594             $hold = $holds[0];
2595         }
2596     }
2597
2598     return $hold;
2599 }
2600
2601 # Standalone, "helper" functions.  These do not take an object or
2602 # class reference.
2603
2604 # Check if a user is past their expiration date.
2605 sub _expired {
2606     my $user = shift;
2607     my $expired = 0;
2608
2609     # Users might not expire.  If so, they have no expire_date.
2610     if ($user->expire_date()) {
2611         my $expires = DateTime::Format::ISO8601->parse_datetime(
2612             cleanse_ISO8601($user->expire_date())
2613         )->epoch();
2614         my $now = DateTime->now()->epoch();
2615         $expired = $now > $expires;
2616     }
2617
2618     return $expired;
2619 }
2620
2621 # Creates a NCIP Problem from an event. Takes a string for the problem
2622 # type, the event hashref (or a string to use for the detail), and
2623 # optional arguments for the ProblemElement and ProblemValue fields.
2624 sub _problem_from_event {
2625     my ($type, $evt, $element, $value) = @_;
2626
2627     my $detail;
2628
2629     # Check the event.
2630     if (ref($evt)) {
2631         my ($textcode, $desc);
2632
2633         # Get the textcode, if available. Otherwise, use the ilsevent
2634         # "id," if available.
2635         if ($evt->{textcode}) {
2636             $textcode = $evt->{textcode};
2637         } elsif ($evt->{ilsevent}) {
2638             $textcode = $evt->{ilsevent};
2639         }
2640
2641         # Get the description. We favor translated descriptions over
2642         # the English in ils_events.xml.
2643         if ($evt->{desc}) {
2644             $desc = $evt->{desc};
2645         }
2646
2647         # Check if $type was set. As an "undocumented" feature, you
2648         # can pass undef, and we'll use the textcode from the event.
2649         unless ($type) {
2650             if ($textcode) {
2651                 $type = $textcode;
2652             }
2653         }
2654
2655         # Set the detail from some combination of the above.
2656         if ($desc) {
2657             $detail = $desc;
2658         } elsif ($textcode eq 'PERM_FAILURE') {
2659             if ($evt->{ilsperm}) {
2660                 $detail = "Permission denied: " . $evt->{ilsperm};
2661                 $detail =~ s/\.override$//;
2662             }
2663         } elsif ($textcode) {
2664             $detail = "ILS returned $textcode error.";
2665         } else {
2666             $detail = 'Detail not available.';
2667         }
2668
2669     } else {
2670         $detail = $evt;
2671     }
2672
2673     return NCIP::Problem->new(
2674         {
2675             ProblemType => ($type) ? $type : 'Temporary Processing Failure',
2676             ProblemDetail => ($detail) ? $detail : 'Detail not available.',
2677             ProblemElement => ($element) ? $element : 'NULL',
2678             ProblemValue => ($value) ? $value : 'NULL'
2679         }
2680     );
2681 }
2682
2683 1;