]> git.evergreen-ils.org Git - working/NCIPServer.git/blob - lib/NCIP/ILS/Evergreen.pm
Fixup a lot of stuff based on a first round of real testing.
[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 use NCIP::Item::OptionalFields;
56 use NCIP::Item::BibliographicDescription;
57 use NCIP::Item::BibliographicItemId;
58 use NCIP::Item::BibliographicRecordId;
59 use NCIP::Item::Description;
60
61 # Inherit from NCIP::ILS.
62 use parent qw(NCIP::ILS);
63
64 =head1 NAME
65
66 Evergreen - Evergreen driver for NCIPServer
67
68 =head1 SYNOPSIS
69
70     my $ils = NCIP::ILS::Evergreen->new(name => $config->{NCIP.ils.value});
71
72 =head1 DESCRIPTION
73
74 NCIP::ILS::Evergreen is the default driver for Evergreen and
75 NCIPServer. It was initially developed to work with Auto-Graphics'
76 SHAREit software using a subset of an unspecified ILL/DCB profile.
77
78 =cut
79
80 # Default values we define for things that might be missing in our
81 # runtime environment or configuration file that absolutely must have
82 # values.
83 #
84 # OILS_NCIP_CONFIG_DEFAULT is the default location to find our
85 # driver's configuration file.  This location can be overridden by
86 # setting the path in the OILS_NCIP_CONFIG environment variable.
87 #
88 # BIB_SOURCE_DEFAULT is the config.bib_source.id to use when creating
89 # "short" bibs.  It is used only if no entry is supplied in the
90 # configuration file.  The provided default is 2, the id of the
91 # "System Local" source that comes with a default Evergreen
92 # installation.
93 use constant {
94     OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
95     BIB_SOURCE_DEFAULT => 2
96 };
97
98 # A common Evergreen code shortcut to use AppUtils:
99 my $U = 'OpenILS::Application::AppUtils';
100
101 # The usual constructor:
102 sub new {
103     my $class = shift;
104     $class = ref($class) if (ref $class);
105
106     # Instantiate our parent with the rest of the arguments.  It
107     # creates a blessed hashref.
108     my $self = $class->SUPER::new(@_);
109
110     # Look for our configuration file, load, and parse it:
111     $self->_configure();
112
113     # Bootstrap OpenSRF and prepare some OpenILS components.
114     $self->_bootstrap();
115
116     # Initialize the rest of our internal state.
117     $self->_init();
118
119     return $self;
120 }
121
122 =head1 HANDLER METHODS
123
124 =head2 lookupuser
125
126     $ils->lookupuser($request);
127
128 Processes a LookupUser request.
129
130 =cut
131
132 sub lookupuser {
133     my $self = shift;
134     my $request = shift;
135
136     # Check our session and login if necessary.
137     $self->login() unless ($self->checkauth());
138
139     my $message_type = $self->parse_request_type($request);
140
141     # Let's go ahead and create our response object. We need this even
142     # if there is a problem.
143     my $response = NCIP::Response->new({type => $message_type . "Response"});
144     $response->header($self->make_header($request));
145
146     # Need to parse the request object to get the user barcode.
147     my ($barcode, $idfield) = $self->find_user_barcode($request);
148
149     # If we did not find a barcode, then report the problem.
150     if (ref($barcode) eq 'NCIP::Problem') {
151         $response->problem($barcode);
152         return $response;
153     }
154
155     # Look up our patron by barcode:
156     my $user = $self->retrieve_user_by_barcode($barcode, $idfield);
157     if (ref($user) eq 'NCIP::Problem') {
158         $response->problem($user);
159         return $response;
160     }
161
162     # We got the information, so lets fill in our userdata.
163     my $userdata = NCIP::User->new();
164
165     # Make an array of the user's active barcodes.
166     my $ids = [];
167     foreach my $card (@{$user->cards()}) {
168         if ($U->is_true($card->active())) {
169             my $id = NCIP::User::Id->new({
170                 UserIdentifierType => 'Barcode',
171                 UserIdentifierValue => $card->barcode()
172             });
173             push(@$ids, $id);
174         }
175     }
176     $userdata->UserId($ids);
177
178     # Check if they requested any optional fields and return those.
179     my $elements = $request->{$message_type}->{UserElementType};
180     if ($elements) {
181         $elements = [$elements] unless (ref $elements eq 'ARRAY');
182         my $optionalfields = $self->handle_user_elements($user, $elements);
183         $userdata->UserOptionalFields($optionalfields);
184     }
185
186     $response->data($userdata);
187
188     return $response;
189 }
190
191 =head2 acceptitem
192
193     $ils->acceptitem($request);
194
195 Processes an AcceptItem request.
196
197 =cut
198
199 sub acceptitem {
200     my $self = shift;
201     my $request = shift;
202
203     # Check our session and login if necessary.
204     $self->login() unless ($self->checkauth());
205
206     # Common preparation.
207     my $message = $self->parse_request_type($request);
208     my $response = NCIP::Response->new({type => $message . 'Response'});
209     $response->header($self->make_header($request));
210
211     # We only accept holds for the time being.
212     if ($request->{$message}->{RequestedActionType} =~ /^hold\W/i) {
213         # We need the item id or we can't do anything at all.
214         my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
215         if (ref($item_barcode) eq 'NCIP::Problem') {
216             $response->problem($item_barcode);
217             return $response;
218         }
219
220         # We need to find a patron barcode or we can't look anyone up
221         # to place a hold.
222         my ($user_barcode, $user_idfield) = $self->find_user_barcode($request, 'UserIdentifierValue');
223         if (ref($user_barcode) eq 'NCIP::Problem') {
224             $response->problem($user_barcode);
225             return $response;
226         }
227         # Look up our patron by barcode:
228         my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
229         if (ref($user) eq 'NCIP::Problem') {
230             $response->problem($user);
231             return $response;
232         }
233         # We're doing patron checks before looking for bibliographic
234         # information and creating the item because problems with the
235         # patron are more likely to occur.
236         my $problem = $self->check_user_for_problems($user, 'HOLD');
237         if ($problem) {
238             $response->problem($problem);
239             return $response;
240         }
241
242         # Check if the item barcode already exists:
243         my $item = $self->retrieve_copy_details_by_barcode($item_barcode);
244         if ($item) {
245             # What to do here was not defined in the
246             # specification. Since the copies that we create this way
247             # should get deleted when checked in, it would be an error
248             # if we try to create another one. It means that something
249             # has gone wrong somewhere.
250             $response->problem(
251                 NCIP::Problem->new(
252                     {
253                         ProblemType => 'Duplicate Item',
254                         ProblemDetail => "Item with barcode $item_barcode already exists.",
255                         ProblemElement => $item_idfield,
256                         ProblemValue => $item_barcode
257                     }
258                 )
259             );
260             return $response;
261         }
262
263         # Now, we have to create our new copy and/or bib and call number.
264
265         # First, we have to gather the necessary information from the
266         # request.  Store in a hashref for convenience. We may write a
267         # method to get this information in the future if we find we
268         # need it in other handlers. Such a function would be a
269         # candidate to go into our parent, NCIP::ILS.
270         my $item_info = {
271             barcode => $item_barcode,
272             call_number => $request->{$message}->{ItemOptionalFields}->{ItemDescription}->{CallNumber},
273             title => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Author},
274             author => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Title},
275             publisher => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Publisher},
276             publication_date => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{PublicationDate},
277             medium => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{MediumType},
278             electronic => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{ElectronicResource}
279         };
280
281         if ($self->{config}->{items}->{use_precats}) {
282             # We only need to create a precat copy.
283             $item = $self->create_precat_copy($item_info);
284         } else {
285             # We have to create a "partial" bib record, a call number and a copy.
286             $item = $self->create_fuller_copy($item_info);
287         }
288
289         # If we failed to create the copy, report a problem.
290         unless ($item) {
291             $response->problem(
292                 {
293                     ProblemType => 'Temporary Processing Failure',
294                     ProblemDetail => 'Failed to create the item in the system',
295                     ProblemElement => $item_idfield,
296                     ProblemValue => $item_barcode
297                 }
298             );
299             return $response;
300         }
301
302         # We try to find the pickup location in our database. It's OK
303         # if it does not exist, the user's home library will be used
304         # instead.
305         my $location = $request->{$message}->{PickupLocation};
306         if ($location) {
307             $location = $self->retrieve_org_unit_by_shortname($location);
308         }
309
310         # Now, we place the hold on the newly created copy on behalf
311         # of the patron retrieved above.
312         my $hold = $self->place_hold($item, $user, $location);
313         if (ref($hold) eq 'NCIP::Problem') {
314             $response->problem($hold);
315             return $response;
316         }
317
318         # We return the RequestId and optionally, the ItemID. We'll
319         # just return what was sent to us, since we ignored all of it
320         # but the barcode.
321         my $data = {};
322         $data->{RequestId} = NCIP::RequestId->new(
323             {
324                 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
325                 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
326                 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
327             }
328         );
329         $data->{ItemId} = NCIP::Item::Id->new(
330             {
331                 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
332                 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
333                 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
334             }
335         );
336         $response->data($data);
337
338     } else {
339         my $problem = NCIP::Problem->new();
340         $problem->ProblemType('Unauthorized Combination Of Element Values For System');
341         $problem->ProblemDetail('We only support Hold For Pickup');
342         $problem->ProblemElement('RequestedActionType');
343         $problem->ProblemValue($request->{$message}->{RequestedActionType});
344         $response->problem($problem);
345     }
346
347     return $response;
348 }
349
350 =head2 checkinitem
351
352     $response = $ils->checkinitem($request);
353
354 Checks the item in if we can find the barcode in the message. It
355 returns problems if it cannot find the item in the system or if the
356 item is not checked out.
357
358 It could definitely use some more brains at some point as it does not
359 fully support everything that the standard allows. It also does not
360 really check if the checkin succeeded or not.
361
362 =cut
363
364 sub checkinitem {
365     my $self = shift;
366     my $request = shift;
367
368     # Check our session and login if necessary:
369     $self->login() unless ($self->checkauth());
370
371     # Common stuff:
372     my $message = $self->parse_request_type($request);
373     my $response = NCIP::Response->new({type => $message . 'Response'});
374     $response->header($self->make_header($request));
375
376     # We need the copy barcode from the message.
377     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
378     if (ref($item_barcode) eq 'NCIP::Problem') {
379         $response->problem($item_barcode);
380         return $response;
381     }
382
383     # Retrieve the copy details.
384     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
385     unless ($details) {
386         # Return an Unknown Item problem unless we find the copy.
387         $response->problem(
388             NCIP::Problem->new(
389                 {
390                     ProblemType => 'Unknown Item',
391                     ProblemDetail => "Item with barcode $item_barcode is not known.",
392                     ProblemElement => $item_idfield,
393                     ProblemValue => $item_barcode
394                 }
395             )
396         );
397         return $response;
398     }
399
400     # Check if a UserId was provided. If so, this is the patron to
401     # whom the copy should be checked out.
402     my $user;
403     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
404     # We ignore the problem, because the UserId is optional.
405     if (ref($user_barcode) ne 'NCIP::Problem') {
406         $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
407         # We don't ignore a problem here, however.
408         if (ref($user) eq 'NCIP::Problem') {
409             $response->problem($user);
410             return $response;
411         }
412     }
413
414     # Isolate the copy.
415     my $copy = $details->{copy};
416
417     # Look for a circulation and examine its information:
418     my $circ = $details->{circ};
419
420     # Check the circ details to see if the copy is checked out and, if
421     # the patron was provided, that it is checked out to the patron in
422     # question. We also verify the copy ownership and circulation
423     # location.
424     my $problem = $self->check_circ_details($circ, $copy, $user);
425     if ($problem) {
426         # We need to fill in some information, however.
427         if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
428             $problem->ProblemValue($user_barcode);
429             $problem->ProblemElement($user_idfield);
430         } elsif (!$problem->ProblemElement()) {
431             $problem->ProblemElement($item_idfield);
432         }
433         $response->problem($problem);
434         return $response;
435     }
436
437     # Checkin parameters. We want to skip hold targeting or making
438     # transits, to force the checkin despite the copy status, as
439     # well as void overdues.
440     my $params = {
441         copy_barcode => $copy->barcode(),
442         force => 1,
443         noop => 1,
444         void_overdues => 1
445     };
446     my $result = $U->simplereq(
447         'open-ils.circ',
448         'open-ils.circ.checkin.override',
449         $self->{session}->{authtoken},
450         $params
451     );
452     if (ref($result) eq 'ARRAY') {
453         $result = $result->[0];
454     }
455     if ($result->{textcode} eq 'SUCCESS') {
456         # Delete the copy. Since delete_copy checks ownership
457         # before attempting to delete the copy, we don't bother
458         # checking who owns it.
459         $self->delete_copy($copy);
460         # We need the circulation user for the information below, so we retrieve it.
461         my $circ_user = $self->retrieve_user_by_id($circ->usr());
462         my $data = {
463             ItemId => NCIP::Item::Id->new(
464                 {
465                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
466                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
467                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
468                 }
469             ),
470             UserId => NCIP::User::Id->new(
471                 {
472                     UserIdentifierType => 'Barcode Id',
473                     UserIdentifierValue => $circ_user->card->barcode()
474                 }
475             )
476         };
477
478         # Look for UserElements requested and add it to the response:
479         my $elements = $request->{$message}->{UserElementType};
480         if ($elements) {
481             $elements = [$elements] unless (ref $elements eq 'ARRAY');
482             my $optionalfields = $self->handle_user_elements($circ_user, $elements);
483             $data->{UserOptionalFields} = $optionalfields;
484         }
485         $elements = $request->{$message}->{ItemElementType};
486         if ($elements) {
487             $elements = [$elements] unless (ref $elements eq 'ARRAY');
488             my $optionalfields = $self->handle_item_elements($copy, $elements);
489             $data->{ItemOptionalFields} = $optionalfields;
490         }
491
492         $response->data($data);
493
494         # At some point in the future, we should probably check if
495         # they requested optional user or item elements and return
496         # those. For the time being, we ignore those at the risk of
497         # being considered non-compliant.
498     } else {
499         $response->problem(_problem_from_event('Checkin Failed', $result));
500     }
501
502     return $response
503 }
504
505 =head2 renewitem
506
507     $response = $ils->renewitem($request);
508
509 Handle the RenewItem message.
510
511 =cut
512
513 sub renewitem {
514     my $self = shift;
515     my $request = shift;
516
517     # Check our session and login if necessary:
518     $self->login() unless ($self->checkauth());
519
520     # Common stuff:
521     my $message = $self->parse_request_type($request);
522     my $response = NCIP::Response->new({type => $message . 'Response'});
523     $response->header($self->make_header($request));
524
525     # We need the copy barcode from the message.
526     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
527     if (ref($item_barcode) eq 'NCIP::Problem') {
528         $response->problem($item_barcode);
529         return $response;
530     }
531
532     # Retrieve the copy details.
533     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
534     unless ($details) {
535         # Return an Unknown Item problem unless we find the copy.
536         $response->problem(
537             NCIP::Problem->new(
538                 {
539                     ProblemType => 'Unknown Item',
540                     ProblemDetail => "Item with barcode $item_barcode is not known.",
541                     ProblemElement => $item_idfield,
542                     ProblemValue => $item_barcode
543                 }
544             )
545         );
546         return $response;
547     }
548
549     # User is required for RenewItem.
550     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
551     if (ref($user_barcode) eq 'NCIP::Problem') {
552         $response->problem($user_barcode);
553         return $response;
554     }
555     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
556     if (ref($user) eq 'NCIP::Problem') {
557         $response->problem($user);
558         return $response;
559     }
560
561     # Isolate the copy.
562     my $copy = $details->{copy};
563
564     # Look for a circulation and examine its information:
565     my $circ = $details->{circ};
566
567     # Check the circ details to see if the copy is checked out and, if
568     # the patron was provided, that it is checked out to the patron in
569     # question. We also verify the copy ownership and circulation
570     # location.
571     my $problem = $self->check_circ_details($circ, $copy, $user);
572     if ($problem) {
573         # We need to fill in some information, however.
574         if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
575             $problem->ProblemValue($user_barcode);
576             $problem->ProblemElement($user_idfield);
577         } elsif (!$problem->ProblemElement()) {
578             $problem->ProblemElement($item_idfield);
579         }
580         $response->problem($problem);
581         return $response;
582     }
583
584     # Check if user is blocked from renewals:
585     $problem = $self->check_user_for_problems($user, 'RENEW');
586     if ($problem) {
587         # Replace the ProblemElement and ProblemValue fields.
588         $problem->ProblemElement($user_idfield);
589         $problem->ProblemValue($user_barcode);
590         $response->problem($problem);
591         return $response;
592     }
593
594     # Check if the duration rule allows renewals. It should have been
595     # fleshed during the copy details retrieve.
596     my $rule = $circ->duration_rule();
597     unless (ref($rule)) {
598         $rule = $U->simplereq(
599             'open-ils.pcrud',
600             'open-ils.pcrud.retrieve.crcd',
601             $self->{session}->{authtoken},
602             $rule
603         )->gather(1);
604     }
605     if ($rule->max_renewals() < 1) {
606         $response->problem(
607             NCIP::Problem->new(
608                 {
609                     ProblemType => 'Item Not Renewable',
610                     ProblemDetail => 'Item may not be renewed.',
611                     ProblemElement => $item_idfield,
612                     ProblemValue => $item_barcode
613                 }
614             )
615         );
616         return $response;
617     }
618
619     # Check if there are renewals remaining on the latest circ:
620     if ($circ->renewal_remaining() < 1) {
621         $response->problem(
622             NCIP::Problem->new(
623                 {
624                     ProblemType => 'Maximum Renewals Exceeded',
625                     ProblemDetail => 'Renewal cannot proceed because the User has already renewed the Item the maximum number of times permitted.',
626                     ProblemElement => $item_idfield,
627                     ProblemValue => $item_barcode
628                 }
629             )
630         );
631         return $response;
632     }
633
634     # Now, we attempt the renewal. If it fails, we simply say that the
635     # user is not allowed to renew this item, without getting into
636     # details.
637     my $params = {
638         copy_id => $copy->id(),
639         patron_id => $user->id(),
640         sip_renewal => 1
641     };
642     my $r = $U->simplereq(
643         'open-ils.circ',
644         'open-ils.circ.renew.override',
645         $self->{session}->{authtoken},
646         $params
647     )->gather(1);
648
649     # We only look at the first one, since more than one usually means
650     # failure.
651     if (ref($r) eq 'ARRAY') {
652         $r = $r->[0];
653     }
654     if ($r->{textcode} ne 'SUCCESS') {
655         $problem = _problem_from_event('Renewal Failed', $r);
656         $response->problem($problem);
657     } else {
658         my $data = {
659             ItemId => NCIP::Item::Id->new(
660                 {
661                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
662                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
663                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
664                 }
665             ),
666             UserId => NCIP::User::Id->new(
667                 {
668                     UserIdentifierType => 'Barcode Id',
669                     UserIdentifierValue => $user->card->barcode()
670                 }
671             )
672         };
673         # We need to retrieve the copy details again to refresh our
674         # circ information to get the new due date.
675         $details = $self->retrieve_copy_details_by_barcode($item_barcode);
676         $circ = $details->{circ};
677         $data->{DateDue} = _fix_date($circ->due_date());
678
679         # Look for UserElements requested and add it to the response:
680         my $elements = $request->{$message}->{UserElementType};
681         if ($elements) {
682             $elements = [$elements] unless (ref $elements eq 'ARRAY');
683             my $optionalfields = $self->handle_user_elements($user, $elements);
684             $data->{UserOptionalFields} = $optionalfields;
685         }
686         $elements = $request->{$message}->{ItemElementType};
687         if ($elements) {
688             $elements = [$elements] unless (ref $elements eq 'ARRAY');
689             my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
690             $data->{ItemOptionalFields} = $optionalfields;
691         }
692
693         $response->data($data);
694     }
695
696     # At some point in the future, we should probably check if
697     # they requested optional user or item elements and return
698     # those. For the time being, we ignore those at the risk of
699     # being considered non-compliant.
700
701     return $response;
702 }
703
704 =head2 checkoutitem
705
706     $response = $ils->checkoutitem($request);
707
708 Handle the Checkoutitem message.
709
710 =cut
711
712 sub checkoutitem {
713     my $self = shift;
714     my $request = shift;
715
716     # Check our session and login if necessary:
717     $self->login() unless ($self->checkauth());
718
719     # Common stuff:
720     my $message = $self->parse_request_type($request);
721     my $response = NCIP::Response->new({type => $message . 'Response'});
722     $response->header($self->make_header($request));
723
724     # We need the copy barcode from the message.
725     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
726     if (ref($item_barcode) eq 'NCIP::Problem') {
727         $response->problem($item_barcode);
728         return $response;
729     }
730
731     # Retrieve the copy details.
732     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
733     unless ($details) {
734         # Return an Unknown Item problem unless we find the copy.
735         $response->problem(
736             NCIP::Problem->new(
737                 {
738                     ProblemType => 'Unknown Item',
739                     ProblemDetail => "Item with barcode $item_barcode is not known.",
740                     ProblemElement => $item_idfield,
741                     ProblemValue => $item_barcode
742                 }
743             )
744         );
745         return $response;
746     }
747
748     # User is required for CheckOutItem.
749     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
750     if (ref($user_barcode) eq 'NCIP::Problem') {
751         $response->problem($user_barcode);
752         return $response;
753     }
754     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
755     if (ref($user) eq 'NCIP::Problem') {
756         $response->problem($user);
757         return $response;
758     }
759
760     # Isolate the copy.
761     my $copy = $details->{copy};
762
763     # Check if the copy can circulate.
764     unless ($self->copy_can_circulate($copy)) {
765         $response->problem(
766             NCIP::Problem->new(
767                 {
768                     ProblemType => 'Item Does Not Circulate',
769                     ProblemDetail => "Item with barcode $item_barcode does not circulate.",
770                     ProblemElement => $item_idfield,
771                     ProblemValue => $item_barcode
772                 }
773             )
774         );
775         return $response;
776     }
777
778     # Look for a circulation and examine its information:
779     my $circ = $details->{circ};
780
781     # Check if the item is already checked out.
782     if ($circ && !$circ->checkin_time()) {
783         $response->problem(
784             NCIP::Problem->new(
785                 {
786                     ProblemType => 'Item Already Checked Out',
787                     ProblemDetail => "Item with barcode $item_barcode is already checked out.",
788                     ProblemElement => $item_idfield,
789                     ProblemValue => $item_barcode
790                 }
791             )
792         );
793         return $response;
794     }
795
796     # Check if user is blocked from circulation:
797     my $problem = $self->check_user_for_problems($user, 'CIRC');
798     if ($problem) {
799         # Replace the ProblemElement and ProblemValue fields.
800         $problem->ProblemElement($user_idfield);
801         $problem->ProblemValue($user_barcode);
802         $response->problem($problem);
803         return $response;
804     }
805
806     # Now, we attempt the check out. If it fails, we simply say that
807     # the user is not allowed to check out this item, without getting
808     # into details.
809     my $params = {
810         copy_id => $copy->id(),
811         patron_id => $user->id(),
812     };
813     my $r = $U->simplereq(
814         'open-ils.circ',
815         'open-ils.circ.checkout.full.override',
816         $self->{session}->{authtoken},
817         $params
818     );
819
820     # We only look at the first one, since more than one usually means
821     # failure.
822     if (ref($r) eq 'ARRAY') {
823         $r = $r->[0];
824     }
825     if ($r->{textcode} ne 'SUCCESS') {
826         $problem = _problem_from_event('Check Out Failed', $r);
827         $response->problem($problem);
828     } else {
829         my $data = {
830             ItemId => NCIP::Item::Id->new(
831                 {
832                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
833                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
834                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
835                 }
836             ),
837             UserId => NCIP::User::Id->new(
838                 {
839                     UserIdentifierType => 'Barcode Id',
840                     UserIdentifierValue => $user->card->barcode()
841                 }
842             )
843         };
844         # We need to retrieve the copy details again to refresh our
845         # circ information to get the due date.
846         $details = $self->retrieve_copy_details_by_barcode($item_barcode);
847         $circ = $details->{circ};
848         $data->{DateDue} = _fix_date($circ->due_date());
849
850         # Look for UserElements requested and add it to the response:
851         my $elements = $request->{$message}->{UserElementType};
852         if ($elements) {
853             $elements = [$elements] unless (ref $elements eq 'ARRAY');
854             my $optionalfields = $self->handle_user_elements($user, $elements);
855             $data->{UserOptionalFields} = $optionalfields;
856         }
857         $elements = $request->{$message}->{ItemElementType};
858         if ($elements) {
859             $elements = [$elements] unless (ref $elements eq 'ARRAY');
860             my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
861             $data->{ItemOptionalFields} = $optionalfields;
862         }
863
864         $response->data($data);
865     }
866
867     # At some point in the future, we should probably check if
868     # they requested optional user or item elements and return
869     # those. For the time being, we ignore those at the risk of
870     # being considered non-compliant.
871
872     return $response;
873 }
874
875 =head2 requestitem
876
877     $response = $ils->requestitem($request);
878
879 Handle the NCIP RequestItem message.
880
881 =cut
882
883 sub requestitem {
884     my $self = shift;
885     my $request = shift;
886     # Check our session and login if necessary:
887     $self->login() unless ($self->checkauth());
888
889     # Common stuff:
890     my $message = $self->parse_request_type($request);
891     my $response = NCIP::Response->new({type => $message . 'Response'});
892     $response->header($self->make_header($request));
893
894     # Because we need to have a user to place a hold, because the user
895     # is likely to have problems, and because getting the item
896     # information for the hold is trickier than getting the user
897     # information, we'll do the user first and short circuit out of
898     # the function if there is a problem with the user.
899     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
900     if (ref($user_barcode) eq 'NCIP::Problem') {
901         $response->problem($user_barcode);
902         return $response;
903     }
904     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
905     if (ref($user) eq 'NCIP::Problem') {
906         $response->problem($user);
907         return $response;
908     }
909     my $problem = $self->check_user_for_problems($user, 'HOLD');
910     if ($problem) {
911         $response->problem($problem);
912         return $response;
913     }
914
915     # RequestItem is a blast. We need to check if we have a copy
916     # barcode and/or if we have BibliographicIds. If we have both or
917     # either, we then need to figure out what we're placing the hold
918     # on, a copy, a volume or a bib. We don't currently do part holds,
919     # but maybe we should some day. We can also be sent more than 1
920     # BibliographicId, so we look for certain identifiers first, and
921     # then others in decreasing preference: SYSNUMBER, ISBN, and ISSN.
922
923     # Not to mention that there are two kinds of BibliographicId field
924     # with different field names, and both can be intermixed in an
925     # incoming message! (I just /love/ this nonsense.)
926
927     # This here is the thing we're going to put on hold:
928     my $item;
929
930     # We need copy details if we find in a couple of places below.
931     my $copy_details;
932
933     # We need the copy barcode from the message.
934     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
935     if (ref($item_barcode) ne 'NCIP::Problem') {
936         # Retrieve the copy details.
937         $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
938         unless ($copy_details) {
939             # Return an Unknown Item problem unless we find the copy.
940             $response->problem(
941                 NCIP::Problem->new(
942                     {
943                         ProblemType => 'Unknown Item',
944                         ProblemDetail => "Item with barcode $item_barcode is not known.",
945                         ProblemElement => $item_idfield,
946                         ProblemValue => $item_barcode
947                     }
948                 )
949             );
950             return $response;
951         }
952         $item = $copy_details->{volume}; # We place a volume hold.
953     }
954
955     # We weren't given copy information to target, or we can't find
956     # it, so we need to look for a target via BibliographicId.
957     unless ($item) {
958         my @biblio_ids = $self->find_bibliographic_ids($request);
959         if (@biblio_ids) {
960             $item = $self->find_target_via_bibliographic_id(@biblio_ids);
961         }
962     }
963
964     # If we don't have an item, then blow up with a problem that may
965     # have been set when we went looking for the ItemId.
966     unless ($item) {
967         if (ref($item_barcode) eq 'NCIP::Problem') {
968             $response->problem($item_barcode);
969         } else {
970             $response->problem(
971                 NCIP::Problem->new(
972                     {
973                         ProblemType => 'Request Item Not Found',
974                         ProblemDetail => 'Unable to determine the item to request from input message.',
975                         ProblemElement => 'NULL',
976                         ProblemValue => 'NULL'
977                     }
978                 )
979             );
980         }
981         return $response;
982     } elsif (ref($item) eq 'NCIP::Problem') {
983         $response->problem($item);
984         return $response;
985     }
986
987     # See if we were given a PickupLocation.
988     my $location;
989     if ($request->{$message}->{PickupLocation}) {
990         my $loc = $request->{$message}->{PickupLocation};
991         $loc =~ s/^.*://; # strip everything up to the last
992                           # semi-colon, if any.
993         $location = $self->retrieve_org_unit_by_shortname($loc);
994     }
995
996     # Look for a NeedBeforeDate to use as expiration...
997     my $hold_expiration = $request->{$message}->{NeedBeforeDate};
998
999     # Place the hold.
1000     my $hold = $self->place_hold($item, $user, $location, $hold_expiration);
1001     if (ref($hold) eq 'NCIP::Problem') {
1002         $response->problem($hold);
1003     } else {
1004         my $data = {
1005             RequestId => NCIP::RequestId->new(
1006                 {
1007                     RequestIdentifierType => 'SYSNUMBER',
1008                     RequestIdentifierValue => $hold->id()
1009                 }
1010             ),
1011             UserId => NCIP::User::Id->new(
1012                 {
1013                     UserIdentifierType => 'Barcode Id',
1014                     UserIdentifierValue => $user->card->barcode()
1015                 }
1016             ),
1017             RequestType => $request->{$message}->{RequestType},
1018             RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1019         };
1020         # Look for UserElements requested and add it to the response:
1021         my $elements = $request->{$message}->{UserElementType};
1022         if ($elements) {
1023             $elements = [$elements] unless (ref $elements eq 'ARRAY');
1024             my $optionalfields = $self->handle_user_elements($user, $elements);
1025             $data->{UserOptionalFields} = $optionalfields;
1026         }
1027         $elements = $request->{$message}->{ItemElementType};
1028         if ($elements) {
1029             $copy_details = $self->find_copy_details_by_item($item) unless ($copy_details);
1030             $elements = [$elements] unless (ref($elements) eq 'ARRAY');
1031             my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1032             $data->{ItemOptionalFields} = $optionalfields;
1033         }
1034
1035         $response->data($data);
1036     }
1037
1038     return $response;
1039 }
1040
1041 =head2 cancelrequestitem
1042
1043     $response = $ils->cancelrequestitem($request);
1044
1045 Handle the NCIP CancelRequestItem message.
1046
1047 =cut
1048
1049 sub cancelrequestitem {
1050     my $self = shift;
1051     my $request = shift;
1052     # Check our session and login if necessary:
1053     $self->login() unless ($self->checkauth());
1054
1055     # Common stuff:
1056     my $message = $self->parse_request_type($request);
1057     my $response = NCIP::Response->new({type => $message . 'Response'});
1058     $response->header($self->make_header($request));
1059
1060     # UserId is required by the standard, but we might not really need it.
1061     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1062     if (ref($user_barcode) eq 'NCIP::Problem') {
1063         $response->problem($user_barcode);
1064         return $response;
1065     }
1066     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1067     if (ref($user) eq 'NCIP::Problem') {
1068         $response->problem($user);
1069         return $response;
1070     }
1071
1072     # See if we got a ItemId and a barcode:
1073     my $copy_details;
1074     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1075     if (ref($item_barcode) ne 'NCIP::Problem') {
1076         # Retrieve the copy details.
1077         $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1078         unless ($copy_details) {
1079             # Return an Unknown Item problem unless we find the copy.
1080             $response->problem(
1081                 NCIP::Problem->new(
1082                     {
1083                         ProblemType => 'Unknown Item',
1084                         ProblemDetail => "Item with barcode $item_barcode is not known.",
1085                         ProblemElement => $item_idfield,
1086                         ProblemValue => $item_barcode
1087                     }
1088                 )
1089             );
1090             return $response;
1091         }
1092     }
1093
1094     # See if we got a RequestId:
1095     my $requestid;
1096     if ($request->{$message}->{RequestId}) {
1097         $requestid = NCIP::RequestId->new(
1098             {
1099                 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1100                 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1101                 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1102             }
1103         )
1104     }
1105
1106     # Just a note: In the below, we cannot rely on the hold or transit
1107     # fields of the copy_details, even if we have retrieved it. This
1108     # is because that hold and transit may not be the ones that we're
1109     # looking for, i.e. they could be for another patron, etc.
1110
1111     # See if we can find the hold:
1112     my $hold;
1113     if ($requestid) {
1114         $hold = $U->simplereq(
1115             'open-ils.pcrud',
1116             'open-ils.pcrud.retrieve.ahr',
1117             $self->{session}->{authtoken},
1118             $requestid->{RequestIdentifierValue},
1119             {flesh => 1, flesh_fields => {ahr => ['transit']}}
1120         );
1121         unless ($hold) {
1122             # Report a problem that we couldn't find a hold by that id.
1123             $response->problem(
1124                 NCIP::Problem->new(
1125                     {
1126                         ProblemType => 'Unknown Request',
1127                         ProblemDetail => 'No request with this identifier found',
1128                         ProblemElement => 'RequestIdentifierValue',
1129                         ProblemValue => $requestid->{RequestIdentifierValue}
1130                     }
1131                 )
1132             )
1133         } elsif ($hold->cancel_time()) {
1134             $response->problem(
1135                 NCIP::Problem->new(
1136                     {
1137                         ProblemType => 'Request Already Canceled',
1138                         ProblemDetail => 'Request has already been canceled',
1139                         ProblemElement => 'RequestIdentifierValue',
1140                         ProblemValue => $requestid->{RequestIdentifierValue}
1141                     }
1142                 )
1143             )
1144         } elsif ($hold->transit()) {
1145             $response->problem(
1146                 NCIP::Problem->new(
1147                     {
1148                         ProblemType => 'Request Already Processed',
1149                         ProblemDetail => 'Request has already been processed',
1150                         ProblemElement => 'RequestIdentifierValue',
1151                         ProblemValue => $requestid->{RequestIdentifierValue}
1152                     }
1153                 )
1154             )
1155         } elsif ($hold->usr() == $user->id()) {
1156             # Check the target matches the copy information, if any,
1157             # that we were given.
1158             my $obj_id;
1159             if ($copy_details) {
1160                 if ($hold->hold_type() eq 'V') {
1161                     $obj_id = $copy_details->{volume}->id();
1162                 } elsif ($hold->hold_type() eq 'T') {
1163                     $obj_id = $copy_details->{mvr}->doc_id();
1164                 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1165                     $obj_id = $copy_details->{copy}->id();
1166                 }
1167             }
1168             if ($obj_id && $hold->target() != $obj_id) {
1169                 $response->problem(
1170                     NCIP::Problem->new(
1171                         {
1172                             ProblemType => 'Request Not For This Item',
1173                             ProblemDetail => "Request is not for this item",
1174                             ProblemElement => $item_idfield,
1175                             ProblemElement => $item_barcode
1176                         }
1177                     )
1178                 )
1179             } else {
1180                 $self->cancel_hold($hold);
1181                 my $data = {
1182                     RequestId => $requestid,
1183                     UserId => NCIP::User::Id->new(
1184                         {
1185                             UserIdentifierType => 'Barcode Id',
1186                             UserIdentifierValue => $user->card->barcode()
1187                         }
1188                     )
1189                 };
1190                 # Look for UserElements requested and add it to the response:
1191                 my $elements = $request->{$message}->{UserElementType};
1192                 if ($elements) {
1193                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1194                     my $optionalfields = $self->handle_user_elements($user, $elements);
1195                     $data->{UserOptionalFields} = $optionalfields;
1196                 }
1197                 $elements = $request->{$message}->{ItemElementType};
1198                 if ($elements && $copy_details) {
1199                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1200                     my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1201                     $data->{ItemOptionalFields} = $optionalfields;
1202                 }
1203                 $response->data($data);
1204             }
1205         } else {
1206             # Report a problem that the hold is not for this user.
1207             $response->problem(
1208                 NCIP::Problem->new(
1209                     {
1210                         ProblemType => 'Request Not For This User',
1211                         ProblemDetail => 'Request is not for this user.',
1212                         ProblemElement => $user_idfield,
1213                         ProblemValue => $user_barcode
1214                     }
1215                 )
1216             )
1217         }
1218     } else {
1219         # At this point, we *must have* an ItemId and therefore
1220         # $copy_details, so return the problem from looking up the
1221         # barcode if we don't have $copy_details.
1222         if (!$copy_details) {
1223             $response->problem($item_barcode);
1224         } else {
1225             # We have to search for the hold based on the copy details and
1226             # the user.  We'll need to search for copy (or force) holds, a
1227             # volume hold, or a title hold.
1228             $hold = $self->_hold_search($user, $copy_details);
1229             if ($hold && $hold->transit()) {
1230                 $response->problem(
1231                     NCIP::Problem->new(
1232                         {
1233                             ProblemType => 'Request Already Processed',
1234                             ProblemDetail => 'Request has already been processed',
1235                             ProblemElement => 'RequestIdentifierValue',
1236                             ProblemValue => $requestid->{RequestIdentifierValue}
1237                         }
1238                     )
1239                 )
1240             } elsif ($hold) {
1241                 $self->cancel_hold($hold);
1242                 my $data = {
1243                     RequestId => NCIP::RequestId->new(
1244                         {
1245                             RequestIdentifierType => 'SYSNUMBER',
1246                             RequestIdentifierValue => $hold->id()
1247                         }
1248                     ),
1249                     UserId => NCIP::User::Id->new(
1250                         {
1251                             UserIdentifierType => 'Barcode Id',
1252                             UserIdentifierValue => $user->card->barcode()
1253                         }
1254                     )
1255                 };
1256                 # Look for UserElements requested and add it to the response:
1257                 my $elements = $request->{$message}->{UserElementType};
1258                 if ($elements) {
1259                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1260                     my $optionalfields = $self->handle_user_elements($user, $elements);
1261                     $data->{UserOptionalFields} = $optionalfields;
1262                 }
1263                 $elements = $request->{$message}->{ItemElementType};
1264                 if ($elements && $copy_details) {
1265                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1266                     my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1267                     $data->{ItemOptionalFields} = $optionalfields;
1268                 }
1269                 $response->data($data);
1270             } else {
1271                 $response->problem(
1272                     NCIP::Problem->new(
1273                         {
1274                             ProblemType => 'Unknown Request',
1275                             ProblemDetail => 'No request found for the item and user',
1276                             ProblemElement => 'NULL',
1277                             ProblemValue => 'NULL'
1278                         }
1279                     )
1280                 )
1281             }
1282         }
1283     }
1284
1285     return $response;
1286 }
1287
1288 =head1 METHODS USEFUL to SUBCLASSES
1289
1290 =head2 handle_user_elements
1291     $useroptionalfield = $ils->handle_user_elements($user, $elements);
1292
1293 Returns NCIP::User::OptionalFields for the given user and arrayref of
1294 UserElement.
1295
1296 =cut
1297
1298 sub handle_user_elements {
1299     my $self = shift;
1300     my $user = shift;
1301     my $elements = shift;
1302     my $optionalfields = NCIP::User::OptionalFields->new();
1303
1304     # First, we'll look for name information.
1305     if (grep {$_ eq 'Name Information'} @$elements) {
1306         my $name = NCIP::StructuredPersonalUserName->new();
1307         $name->Surname($user->family_name());
1308         $name->GivenName($user->first_given_name());
1309         $name->Prefix($user->prefix());
1310         $name->Suffix($user->suffix());
1311         $optionalfields->NameInformation($name);
1312     }
1313
1314     # Next, check for user address information.
1315     if (grep {$_ eq 'User Address Information'} @$elements) {
1316         my $addresses = [];
1317
1318         # See if the user has any valid, physcial addresses.
1319         foreach my $addr (@{$user->addresses()}) {
1320             next if ($U->is_true($addr->pending()));
1321             my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
1322             my $physical = NCIP::StructuredAddress->new();
1323             $physical->Line1($addr->street1());
1324             $physical->Line2($addr->street2());
1325             $physical->Locality($addr->city());
1326             $physical->Region($addr->state());
1327             $physical->PostalCode($addr->post_code());
1328             $physical->Country($addr->country());
1329             $address->PhysicalAddress($physical);
1330             push @$addresses, $address;
1331         }
1332
1333         # Right now, we're only sharing email address if the user
1334         # has it. We don't share phone numbers.
1335         if ($user->email()) {
1336             my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
1337             $address->ElectronicAddress(
1338                 NCIP::ElectronicAddress->new({
1339                     Type=>'Email Address',
1340                     Data=>$user->email()
1341                 })
1342                 );
1343             push @$addresses, $address;
1344         }
1345
1346         $optionalfields->UserAddressInformation($addresses);
1347     }
1348
1349     # Check for User Privilege.
1350     if (grep {$_ eq 'User Privilege'} @$elements) {
1351         # Get the user's group:
1352         my $pgt = $U->simplereq(
1353             'open-ils.pcrud',
1354             'open-ils.pcrud.retrieve.pgt',
1355             $self->{session}->{authtoken},
1356             $user->profile()
1357         );
1358         if ($pgt) {
1359             my $privilege = NCIP::User::Privilege->new();
1360             $privilege->AgencyId($user->home_ou->shortname());
1361             $privilege->AgencyUserPrivilegeType($pgt->name());
1362             $privilege->ValidToDate(_fix_date($user->expire_date()));
1363             $privilege->ValidFromDate(_fix_date($user->create_date()));
1364
1365             my $status = 'Active';
1366             if (_expired($user)) {
1367                 $status = 'Expired';
1368             } elsif ($U->is_true($user->barred())) {
1369                 $status = 'Barred';
1370             } elsif (!$U->is_true($user->active())) {
1371                 $status = 'Inactive';
1372             }
1373             if ($status) {
1374                 $privilege->UserPrivilegeStatus(
1375                     NCIP::User::PrivilegeStatus->new({
1376                         UserPrivilegeStatusType => $status
1377                     })
1378                 );
1379             }
1380
1381             $optionalfields->UserPrivilege([$privilege]);
1382         }
1383     }
1384
1385     # Check for Block Or Trap.
1386     if (grep {$_ eq 'Block Or Trap'} @$elements) {
1387         my $blocks = [];
1388
1389         # First, let's check if the profile is blocked from ILL.
1390         if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1391             my $block = NCIP::User::BlockOrTrap->new();
1392             $block->AgencyId($user->home_ou->shortname());
1393             $block->BlockOrTrapType('Block Interlibrary Loan');
1394             push @$blocks, $block;
1395         }
1396
1397         # Next, we loop through the user's standing penalties
1398         # looking for blocks on CIRC, HOLD, and RENEW.
1399         my ($have_circ, $have_renew, $have_hold) = (0,0,0);
1400         foreach my $penalty (@{$user->standing_penalties()}) {
1401             next unless($penalty->standing_penalty->block_list());
1402             my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
1403             my $ou = $U->simplereq(
1404                 'open-ils.pcrud',
1405                 'open-ils.pcrud.retrieve.aou',
1406                 $self->{session}->{authtoken},
1407                 $penalty->org_unit()
1408             );
1409
1410             # Block checkout.
1411             if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
1412                 my $bot = NCIP::User::BlockOrTrap->new();
1413                 $bot->AgencyId($ou->shortname());
1414                 $bot->BlockOrTrapType('Block Checkout');
1415                 push @$blocks, $bot;
1416                 $have_circ = 1;
1417             }
1418
1419             # Block holds.
1420             if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
1421                 my $bot = NCIP::User::BlockOrTrap->new();
1422                 $bot->AgencyId($ou->shortname());
1423                 $bot->BlockOrTrapType('Block Holds');
1424                 push @$blocks, $bot;
1425                 $have_hold = 1;
1426             }
1427
1428             # Block renewals.
1429             if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
1430                 my $bot = NCIP::User::BlockOrTrap->new();
1431                 $bot->AgencyId($ou->shortname());
1432                 $bot->BlockOrTrapType('Block Renewals');
1433                 push @$blocks, $bot;
1434                 $have_renew = 1;
1435             }
1436
1437             # Stop after we report one of each, even if more
1438             # blocks remain.
1439             last if ($have_circ && $have_renew && $have_hold);
1440         }
1441
1442         $optionalfields->BlockOrTrap($blocks);
1443     }
1444
1445     return $optionalfields;
1446 }
1447
1448 =head2 handle_item_elements
1449
1450 =cut
1451
1452 sub handle_item_elements {
1453     my $self = shift;
1454     my $copy = shift;
1455     my $elements = shift;
1456     my $optionalfields = NCIP::Item::OptionalFields->new();
1457
1458     my $details; # In case we need for more than one.
1459
1460     if (grep {$_ eq 'Bibliographic Description'} @$elements) {
1461         my $description;
1462         # Check for a precat copy, 'cause it is simple.
1463         if ($copy->dummy_title()) {
1464             $description = NCIP::Item::BibliographicDescription->new();
1465             $description->Title($copy->dummy_title());
1466             $description->Author($copy->dummy_author());
1467             if ($copy->dummy_isbn()) {
1468                 $description->BibliographicItemId(
1469                     NCIP::Item::BibliographicItemId->new(
1470                         {
1471                             BibliographicItemIdentifier => $copy->dummy_isbn(),
1472                             BibliographicItemIdentifierCode => 'ISBN'
1473                         }
1474                     )
1475                 );
1476             }
1477         } else {
1478             $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1479             $description = NCIP::Item::BibliographicDescription->new();
1480             $description->Title($details->{mvr}->title());
1481             $description->Author($details->{mvr}->author());
1482             $description->BibliographicRecordId(
1483                 NCIP::Item::BibliographicRecordId->new(
1484                     {
1485                         BibliographicRecordIdentifier => $details->{mvr}->doc_id(),
1486                         BibliographicRecordIdentifierCode => 'SYSNUMBER'
1487                     }
1488                 )
1489             );
1490             if ($details->{mvr}->publisher()) {
1491                 $description->Publisher($details->{mvr}->publisher());
1492             }
1493             if ($details->{mvr}->pubdate()) {
1494                 $description->PublicationDate($details->{mvr}->pubdate());
1495             }
1496             if ($details->{mvr}->edition()) {
1497                 $description->Edition($details->{mvr}->edition());
1498             }
1499         }
1500         $optionalfields->BibliographicDescription($description) if ($description);
1501     }
1502
1503     if (grep {$_ eq 'Item Description'} @$elements) {
1504         $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1505         # Call Number is the only field we currently return. We also
1506         # do not attempt to retun a prefix and suffix. Someone else
1507         # can deal with that if they want it.
1508         if ($details->{volume}) {
1509             $optionalfields->ItemDescription(
1510                 NCIP::Item::Description->new(
1511                     {CallNumber => $details->{volume}->label()}
1512                 )
1513             );
1514         }
1515     }
1516
1517     if (grep {$_ eq 'Circulation Status'} @$elements) {
1518         my $status = $copy->status();
1519         $status = $self->retrieve_copy_status($status) unless (ref($status));
1520         $optionalfields->CirculationStatus($status->name()) if ($status);
1521     }
1522
1523     if (grep {$_ eq 'Date Due'} @$elements) {
1524         $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1525         if ($details->{circ}) {
1526             if (!$details->{circ}->checkin_time()) {
1527                 $optionalfields->DateDue(_fix_date($details->{circ}->due_date()));
1528             }
1529         }
1530     }
1531
1532     if (grep {$_ eq 'Item Use Restriction Type'} @$elements) {
1533         $optionalfields->ItemUseRestrictionType('None');
1534     }
1535
1536     if (grep {$_ eq 'Physical Condition'} @$elements) {
1537         $optionalfields->PhysicalCondition(
1538             NCIP::Item::PhysicalCondition->new(
1539                 {PhysicalConditionType => 'Unknown'}
1540             )
1541         );
1542     }
1543
1544     return $optionalfields;
1545 }
1546
1547 =head2 login
1548
1549     $ils->login();
1550
1551 Login to Evergreen via OpenSRF. It uses internal state from the
1552 configuration file to login.
1553
1554 =cut
1555
1556 # Login via OpenSRF to Evergreen.
1557 sub login {
1558     my $self = shift;
1559
1560     # Get the authentication seed.
1561     my $seed = $U->simplereq(
1562         'open-ils.auth',
1563         'open-ils.auth.authenticate.init',
1564         $self->{config}->{credentials}->{username}
1565     );
1566
1567     # Actually login.
1568     if ($seed) {
1569         my $response = $U->simplereq(
1570             'open-ils.auth',
1571             'open-ils.auth.authenticate.complete',
1572             {
1573                 username => $self->{config}->{credentials}->{username},
1574                 password => md5_hex(
1575                     $seed . md5_hex($self->{config}->{credentials}->{password})
1576                 ),
1577                 type => 'staff',
1578                 workstation => $self->{config}->{credentials}->{workstation}
1579             }
1580         );
1581         if ($response) {
1582             $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1583             $self->{session}->{authtime} = $response->{payload}->{authtime};
1584
1585             # Set/reset the work_ou and user data in case something changed.
1586
1587             # Retrieve the work_ou as an object.
1588             $self->{session}->{work_ou} = $U->simplereq(
1589                 'open-ils.pcrud',
1590                 'open-ils.pcrud.search.aou',
1591                 $self->{session}->{authtoken},
1592                 {shortname => $self->{config}->{credentials}->{work_ou}}
1593             );
1594
1595             # We need the user information in order to do some things.
1596             $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1597
1598         }
1599     }
1600 }
1601
1602 =head2 checkauth
1603
1604     $valid = $ils->checkauth();
1605
1606 Returns 1 if the object a 'valid' authtoken, 0 if not.
1607
1608 =cut
1609
1610 sub checkauth {
1611     my $self = shift;
1612
1613     # We use AppUtils to do the heavy lifting.
1614     if (defined($self->{session})) {
1615         if ($U->check_user_session($self->{session}->{authtoken})) {
1616             return 1;
1617         } else {
1618             return 0;
1619         }
1620     }
1621
1622     # If we reach here, we don't have a session, so we are definitely
1623     # not logged in.
1624     return 0;
1625 }
1626
1627 =head2 retrieve_user_by_barcode
1628
1629     $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1630
1631 Do a fleshed retrieve of a patron by barcode. Return the patron if
1632 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1633
1634 The id field argument is used for the ProblemElement field in the
1635 NCIP::Problem object.
1636
1637 An invalid patron is one where the barcode is not found in the
1638 database, the patron is deleted, or the barcode used to retrieve the
1639 patron is not active. The problem element is also returned if an error
1640 occurs during the retrieval.
1641
1642 =cut
1643
1644 sub retrieve_user_by_barcode {
1645     my ($self, $barcode, $idfield) = @_;
1646     my $result = $U->simplereq(
1647         'open-ils.actor',
1648         'open-ils.actor.user.fleshed.retrieve_by_barcode',
1649         $self->{session}->{authtoken},
1650         $barcode,
1651         1
1652     );
1653
1654     # Check for a failure, or a deleted, inactive, or expired user,
1655     # and if so, return empty userdata.
1656     if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1657             || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1658
1659         my $problem = NCIP::Problem->new();
1660         $problem->ProblemType('Unknown User');
1661         $problem->ProblemDetail("User with barcode $barcode unknown");
1662         $problem->ProblemElement($idfield);
1663         $problem->ProblemValue($barcode);
1664         $result = $problem;
1665     }
1666
1667     return $result;
1668 }
1669
1670 =head2 retrieve_user_by_id
1671
1672     $user = $ils->retrieve_user_by_id($id);
1673
1674 Similar to C<retrieve_user_by_barcode> but takes the user's database
1675 id rather than barcode. This is useful when you have a circulation or
1676 hold and need to get information about the user's involved in the hold
1677 or circulaiton.
1678
1679 It returns a fleshed user on success or undef on failure.
1680
1681 =cut
1682
1683 sub retrieve_user_by_id {
1684     my ($self, $id) = @_;
1685
1686     # Do a fleshed retrieve of the patron, and flesh the fields that
1687     # we would normally use.
1688     my $result = $U->simplereq(
1689         'open-ils.actor',
1690         'open-ils.actor.user.fleshed.retrieve',
1691         $self->{session}->{authtoken},
1692         $id,
1693         [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1694     );
1695     # Check for an error.
1696     undef($result) if ($result && $U->event_code($result));
1697
1698     return $result;
1699 }
1700
1701 =head2 check_user_for_problems
1702
1703     $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1704
1705 This function checks if a user has a blocked profile or any from a
1706 list of provided blocks. If it does, then a NCIP::Problem object is
1707 returned, otherwise an undefined value is returned.
1708
1709 The list of blocks appears as additional arguments after the user. You
1710 can provide any value(s) that might appear in a standing penalty block
1711 lit in Evergreen. The example above checks for HOLD, CIRC, and
1712 RENEW. Any number of such values can be provided. If none are
1713 provided, the function only checks if the patron's profiles appears in
1714 the object's blocked profiles list.
1715
1716 It stops on the first matching block, if any.
1717
1718 =cut
1719
1720 sub check_user_for_problems {
1721     my $self = shift;
1722     my $user = shift;
1723     my @blocks = @_;
1724
1725     # Fill this in if we have a problem, otherwise just return it.
1726     my $problem;
1727
1728     # First, check the user's profile.
1729     if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1730         $problem = NCIP::Problem->new(
1731             {
1732                 ProblemType => 'User Blocked',
1733                 ProblemDetail => 'User blocked from inter-library loan',
1734                 ProblemElement => 'NULL',
1735                 ProblemValue => 'NULL'
1736             }
1737         );
1738     }
1739
1740     # Next, check if the patron has one of the indicated blocks.
1741     unless ($problem) {
1742         foreach my $penalty (@{$user->standing_penalties()}) {
1743             if ($penalty->standing_penalty->block_list()) {
1744                 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1745                 foreach my $block (@blocks) {
1746                     if (grep {$_ =~ /$block/} @pblocks) {
1747                         $problem = NCIP::Problem->new(
1748                             {
1749                                 ProblemType => 'User Blocked',
1750                                 ProblemDetail => 'User blocked from ' .
1751                                     ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1752                                                                         (($block eq 'CIRC') ? 'checkout' : lc($block))),
1753                                 ProblemElement => 'NULL',
1754                                 ProblemValue => 'NULL'
1755                             }
1756                         );
1757                         last;
1758                     }
1759                 }
1760                 last if ($problem);
1761             }
1762         }
1763     }
1764
1765     return $problem;
1766 }
1767
1768 =head2 check_circ_details
1769
1770     $problem = $ils->check_circ_details($circ, $copy, $user);
1771
1772 Checks if we can checkin or renew a circulation. That is, the
1773 circulation is still open (i.e. the copy is still checked out), if we
1774 either own the copy or are the circulation location, and if the
1775 circulation is for the optional $user argument. $circ and $copy are
1776 required. $user is optional.
1777
1778 Returns a problem if any of the above conditions fail. Returns undef
1779 if they pass and we can proceed with the checkin or renewal.
1780
1781 If the failure occurred on the copy-related checks, then the
1782 ProblemElement field will be undefined and needs to be filled in with
1783 the item id field name. If the check for the copy being checked out to
1784 the provided user fails, then both ProblemElement and ProblemValue
1785 fields will be empty and need to be filled in by the caller.
1786
1787 =cut
1788
1789 sub check_circ_details {
1790     my ($self, $circ, $copy, $user) = @_;
1791
1792     # Shortcut for the next check.
1793     my $ou_id = $self->{session}->{work_ou}->id();
1794
1795     if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1796         # Item isn't checked out.
1797         return NCIP::Problem->new(
1798             {
1799                 ProblemType => 'Item Not Checked Out',
1800                 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1801                 ProblemValue => $copy->barcode()
1802             }
1803         );
1804     } else {
1805         # Get data on the patron who has it checked out.
1806         my $circ_user = $self->retrieve_user_by_id($circ->usr());
1807         if ($user && $circ_user && $user->id() != $circ_user->id()) {
1808             # The ProblemElement and ProblemValue field need to be
1809             # filled in by the caller.
1810             return NCIP::Problem->new(
1811                 {
1812                     ProblemType => 'Item Not Checked Out To This User',
1813                     ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1814                 }
1815             );
1816         }
1817     }
1818     # If we get here, we're good to go.
1819     return undef;
1820 }
1821
1822 =head2 retrieve_copy_details_by_barcode
1823
1824     $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1825
1826 Look up and retrieve some copy details by the copy barcode. This
1827 method returns either a hashref with the copy details or undefined if
1828 no copy exists with that barcode or if some error occurs.
1829
1830 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1831
1832 This method differs from C<retrieve_user_by_barcode> in that a copy
1833 cannot be invalid if it exists and it is not always an error if no
1834 copy exists. In some cases, when handling AcceptItem, we might prefer
1835 there to be no copy.
1836
1837 =cut
1838
1839 sub retrieve_copy_details_by_barcode {
1840     my $self = shift;
1841     my $barcode = shift;
1842
1843     my $copy = $U->simplereq(
1844         'open-ils.circ',
1845         'open-ils.circ.copy_details.retrieve.barcode',
1846         $self->{session}->{authtoken},
1847         $barcode
1848     );
1849
1850     # If $copy is an event, return undefined.
1851     if ($copy && $U->event_code($copy)) {
1852         undef($copy);
1853     }
1854
1855     return $copy;
1856 }
1857
1858 =head2 find_copy_details_by_item
1859
1860     $copy_details = $ils->find_copy_details_by_item($item);
1861
1862 This routine returns a copy_details hashref (See:
1863 retrieve_copy_details_by_barcode) for a given item. It attempts to
1864 find the "first" copy for the given item. If item is a call number it
1865 looks for the first, not deleted copy. If item is a bib, it looks for
1866 the first not deleted copy on the first not deleted call number. If
1867 item is a copy, it simply returns the details for the copy.
1868
1869 =cut
1870
1871 sub find_copy_details_by_item {
1872     my $self = shift;
1873     my $item = shift;
1874
1875     my ($details);
1876
1877     if (ref($item) eq 'Fieldmapper::biblio::record_entry') {
1878         my $acns = $U->simplereq(
1879             'open-ils.pcrud',
1880             'open-ils.pcrud.search.acn.atomic',
1881             $self->{session}->{authtoken},
1882             {
1883                 record => $item->id(),
1884                 deleted => 'f'
1885             }
1886         );
1887         ($item) = sort {$a->id() <=> $b->id()} @{$acns};
1888     }
1889
1890     if (ref($item) eq 'Fieldmapper::asset::call_number') {
1891         my $copies = $U->simplereq(
1892             'open-ils.pcrud',
1893             'open-ils.pcrud.search.acp.atomic',
1894             $self->{session}->{authtoken},
1895             {
1896                 call_number => $item->id(),
1897                 deleted => 'f'
1898             }
1899         );
1900         ($item) = sort {$a->id() <=> $b->id()} @{$copies};
1901     }
1902
1903     if (ref($item) eq 'Fieldmapper::asset::copy') {
1904         $details = $self->retrieve_copy_details_by_barcode($item->barcode());
1905     }
1906
1907     return $details;
1908 }
1909
1910 =head2 retrieve_copy_status
1911
1912     $status = $ils->retrieve_copy_status($id);
1913
1914 Retrive a copy status object by database ID.
1915
1916 =cut
1917
1918 sub retrieve_copy_status {
1919     my $self = shift;
1920     my $id = shift;
1921
1922     my $status = $U->simplereq(
1923         'open-ils.pcrud',
1924         'open-ils.pcrud.retrieve.ccs',
1925         $self->{session}->{authtoken},
1926         $id
1927     );
1928
1929     return $status;
1930 }
1931
1932 =head2 retrieve_org_unit_by_shortname
1933
1934     $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1935
1936 Retrieves an org. unit from the database by shortname. Returns the
1937 org. unit as a Fieldmapper object or undefined.
1938
1939 =cut
1940
1941 sub retrieve_org_unit_by_shortname {
1942     my $self = shift;
1943     my $shortname = shift;
1944
1945     my $aou = $U->simplereq(
1946         'open-ils.actor',
1947         'open-ils.actor.org_unit.retrieve_by_shortname',
1948         $shortname
1949     );
1950
1951     return $aou;
1952 }
1953
1954 =head2 retrieve_copy_location
1955
1956     $location = $ils->retrieve_copy_location($location_id);
1957
1958 Retrieve a copy location based on id.
1959
1960 =cut
1961
1962 sub retrieve_copy_location {
1963     my $self = shift;
1964     my $id = shift;
1965
1966     my $location = $U->simplereq(
1967         'open-ils.pcrud',
1968         'open-ils.pcrud.retrieve.acpl',
1969         $self->{session}->{authtoken},
1970         $id
1971     );
1972
1973     return $location;
1974 }
1975
1976 =head2 retrieve_biblio_record_entry
1977
1978     $bre = $ils->retrieve_biblio_record_entry($bre_id);
1979
1980 Given a biblio.record_entry.id, this method retrieves a bre object.
1981
1982 =cut
1983
1984 sub retrieve_biblio_record_entry {
1985     my $self = shift;
1986     my $id = shift;
1987
1988     my $bre = $U->simplereq(
1989         'open-ils.pcrud',
1990         'open-ils.pcrud.retrieve.bre',
1991         $self->{session}->{authtoken},
1992         $id
1993     );
1994
1995     return $bre;
1996 }
1997
1998 =head2 create_precat_copy
1999
2000     $item_info->{
2001         barcode => '312340123456789',
2002         author => 'Public, John Q.',
2003         title => 'Magnum Opus',
2004         call_number => '005.82',
2005         publisher => 'Brick House',
2006         publication_date => '2014'
2007     };
2008
2009     $item = $ils->create_precat_copy($item_info);
2010
2011
2012 Create a "precat" copy to use for the incoming item using a hashref of
2013 item information. At a minimum, the barcode, author and title fields
2014 need to be filled in. The other fields are ignored if provided.
2015
2016 This method is called by the AcceptItem handler if the C<use_precats>
2017 configuration option is turned on.
2018
2019 =cut
2020
2021 sub create_precat_copy {
2022     my $self = shift;
2023     my $item_info = shift;
2024
2025     my $item = Fieldmapper::asset::copy->new();
2026     $item->barcode($item_info->{barcode});
2027     $item->call_number(OILS_PRECAT_CALL_NUMBER);
2028     $item->dummy_title($item_info->{title});
2029     $item->dummy_author($item_info->{author});
2030     $item->circ_lib($self->{session}->{work_ou}->id());
2031     $item->circulate('t');
2032     $item->holdable('t');
2033     $item->opac_visible('f');
2034     $item->deleted('f');
2035     $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2036     $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2037     $item->location(1);
2038     $item->status(0);
2039     $item->editor($self->{session}->{user}->id());
2040     $item->creator($self->{session}->{user}->id());
2041     $item->isnew(1);
2042
2043     # Actually create it:
2044     my $xact;
2045     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2046     $ses->connect();
2047     eval {
2048         $xact = $ses->request(
2049             'open-ils.pcrud.transaction.begin',
2050             $self->{session}->{authtoken}
2051         )->gather(1);
2052         $item = $ses->request(
2053             'open-ils.pcrud.create.acp',
2054             $self->{session}->{authtoken},
2055             $item
2056         )->gather(1);
2057         $xact = $ses->request(
2058             'open-ils.pcrud.transaction.commit',
2059             $self->{session}->{authtoken}
2060         )->gather(1);
2061     };
2062     if ($@) {
2063         undef($item);
2064         if ($xact) {
2065             eval {
2066                 $ses->request(
2067                     'open-ils.pcrud.transaction.rollback',
2068                     $self->{session}->{authtoken}
2069                 )->gather(1);
2070             };
2071         }
2072     }
2073     $ses->disconnect();
2074
2075     return $item;
2076 }
2077
2078 =head2 create_fuller_copy
2079
2080     $item_info->{
2081         barcode => '31234003456789',
2082         author => 'Public, John Q.',
2083         title => 'Magnum Opus',
2084         call_number => '005.82',
2085         publisher => 'Brick House',
2086         publication_date => '2014'
2087     };
2088
2089     $item = $ils->create_fuller_copy($item_info);
2090
2091 Creates a skeletal bibliographic record, call number, and copy for the
2092 incoming item using a hashref with item information in it. At a
2093 minimum, the barcode, author, title, and call_number fields must be
2094 filled in.
2095
2096 This method is used by the AcceptItem handler if the C<use_precats>
2097 configuration option is NOT set.
2098
2099 =cut
2100
2101 sub create_fuller_copy {
2102     my $self = shift;
2103     my $item_info = shift;
2104
2105     my $item;
2106
2107     # We do everything in one transaction, because it should be atomic.
2108     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2109     $ses->connect();
2110     my $xact;
2111     eval {
2112         $xact = $ses->request(
2113             'open-ils.pcrud.transaction.begin',
2114             $self->{session}->{authtoken}
2115         )->gather(1);
2116     };
2117     if ($@) {
2118         undef($xact);
2119     }
2120
2121     # The rest depends on there being a transaction.
2122     if ($xact) {
2123
2124         # Create the MARC record.
2125         my $record = MARC::Record->new();
2126         $record->encoding('UTF-8');
2127         $record->leader('00881nam a2200193   4500');
2128         my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
2129         my @fields = ();
2130         push(@fields, MARC::Field->new('005', $datespec));
2131         push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
2132         push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
2133         # Publisher is a little trickier:
2134         if ($item_info->{publisher}) {
2135             my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
2136             $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
2137             push(@fields, $pub);
2138         }
2139         # We have no idea if the author is personal corporate or something else, so we use a 720.
2140         push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
2141         $record->append_fields(@fields);
2142         my $marc = clean_marc($record);
2143
2144         # Create the bib object.
2145         my $bib = Fieldmapper::biblio::record_entry->new();
2146         $bib->creator($self->{session}->{user}->id());
2147         $bib->editor($self->{session}->{user}->id());
2148         $bib->source($self->{bib_source}->id());
2149         $bib->active('t');
2150         $bib->deleted('f');
2151         $bib->marc($marc);
2152         $bib->isnew(1);
2153
2154         eval {
2155             $bib = $ses->request(
2156                 'open-ils.pcrud.create.bre',
2157                 $self->{session}->{authtoken},
2158                 $bib
2159             )->gather(1);
2160         };
2161         if ($@) {
2162             undef($bib);
2163             eval {
2164                 $ses->request(
2165                     'open-ils.pcrud.transaction.rollback',
2166                     $self->{session}->{authtoken}
2167                 )->gather(1);
2168             };
2169         }
2170
2171         # Create the call number
2172         my $acn;
2173         if ($bib) {
2174             $acn = Fieldmapper::asset::call_number->new();
2175             $acn->creator($self->{session}->{user}->id());
2176             $acn->editor($self->{session}->{user}->id());
2177             $acn->label($item_info->{call_number});
2178             $acn->record($bib->id());
2179             $acn->owning_lib($self->{session}->{work_ou}->id());
2180             $acn->deleted('f');
2181             $acn->isnew(1);
2182
2183             eval {
2184                 $acn = $ses->request(
2185                     'open-ils.pcrud.create.acn',
2186                     $self->{session}->{authtoken},
2187                     $acn
2188                 )->gather(1);
2189             };
2190             if ($@) {
2191                 undef($acn);
2192                 eval {
2193                     $ses->request(
2194                         'open-ils.pcrud.transaction.rollback',
2195                         $self->{session}->{authtoken}
2196                     )->gather(1);
2197                 };
2198             }
2199         }
2200
2201         # create the copy
2202         if ($acn) {
2203             $item = Fieldmapper::asset::copy->new();
2204             $item->barcode($item_info->{barcode});
2205             $item->call_number($acn->id());
2206             $item->circ_lib($self->{session}->{work_ou}->id);
2207             $item->circulate('t');
2208             if ($self->{config}->{items}->{use_force_holds}) {
2209                 $item->holdable('f');
2210             } else {
2211                 $item->holdable('t');
2212             }
2213             $item->opac_visible('f');
2214             $item->deleted('f');
2215             $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2216             $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2217             $item->location(1);
2218             $item->status(0);
2219             $item->editor($self->{session}->{user}->id);
2220             $item->creator($self->{session}->{user}->id);
2221             $item->isnew(1);
2222
2223             eval {
2224                 $item = $ses->request(
2225                     'open-ils.pcrud.create.acp',
2226                     $self->{session}->{authtoken},
2227                     $item
2228                 )->gather(1);
2229
2230                 # Cross our fingers and commit the work.
2231                 $xact = $ses->request(
2232                     'open-ils.pcrud.transaction.commit',
2233                     $self->{session}->{authtoken}
2234                 )->gather(1);
2235             };
2236             if ($@) {
2237                 undef($item);
2238                 eval {
2239                     $ses->request(
2240                         'open-ils.pcrud.transaction.rollback',
2241                         $self->{session}->{authtoken}
2242                     )->gather(1) if ($xact);
2243                 };
2244             }
2245         }
2246     }
2247
2248     # We need to disconnect our session.
2249     $ses->disconnect();
2250
2251     # Now, we handle our asset stat_cat entries.
2252     if ($item) {
2253         # It would be nice to do these in the above transaction, but
2254         # pcrud does not support the ascecm object, yet.
2255         foreach my $entry (@{$self->{stat_cat_entries}}) {
2256             my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2257             $map->isnew(1);
2258             $map->stat_cat($entry->stat_cat());
2259             $map->stat_cat_entry($entry->id());
2260             $map->owning_copy($item->id());
2261             # We don't really worry if it succeeds or not.
2262             $U->simplereq(
2263                 'open-ils.circ',
2264                 'open-ils.circ.stat_cat.asset.copy_map.create',
2265                 $self->{session}->{authtoken},
2266                 $map
2267             );
2268         }
2269     }
2270
2271     return $item;
2272 }
2273
2274 =head2 place_hold
2275
2276     $hold = $ils->place_hold($item, $user, $location, $expiration);
2277
2278 This function places a hold on $item for $user for pickup at
2279 $location. If location is not provided or undefined, the user's home
2280 library is used as a fallback.
2281
2282 The $expiration argument is optional and must be a properly formatted
2283 ISO date time. It will be used as the hold expire time, if
2284 provided. Otherwise the system default time will be used.
2285
2286 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2287 (biblio::record_entry). The appropriate hold type will be placed
2288 depending on the object.
2289
2290 On success, the method returns the object representing the hold. On
2291 failure, a NCIP::Problem object, describing the failure, is returned.
2292
2293 =cut
2294
2295 sub place_hold {
2296     my $self = shift;
2297     my $item = shift;
2298     my $user = shift;
2299     my $location = shift;
2300     my $expiration = shift;
2301
2302     # If $location is undefined, use the user's home_ou, which should
2303     # have been fleshed when the user was retrieved.
2304     $location = $user->home_ou() unless ($location);
2305
2306     # $hold is the hold. $params is for the is_possible check.
2307     my ($hold, $params);
2308
2309     # Prep the hold with fields common to all hold types:
2310     $hold = Fieldmapper::action::hold_request->new();
2311     $hold->isnew(1); # Just to make sure.
2312     $hold->target($item->id());
2313     $hold->usr($user->id());
2314     $hold->pickup_lib($location->id());
2315     $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2316     if (!$user->email()) {
2317         $hold->email_notify('f');
2318         $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2319     } else {
2320         $hold->email_notify('t');
2321     }
2322
2323     # Ditto the params:
2324     $params = { pickup_lib => $location->id(), patronid => $user->id() };
2325
2326     if (ref($item) eq 'Fieldmapper::asset::copy') {
2327         my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2328         $hold->hold_type($type);
2329         $hold->current_copy($item->id());
2330         $params->{hold_type} = $type;
2331         $params->{copy_id} = $item->id();
2332     } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2333         $hold->hold_type('V');
2334         $params->{hold_type} = 'V';
2335         $params->{volume_id} = $item->id();
2336     } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2337         $hold->hold_type('T');
2338         $params->{hold_type} = 'T';
2339         $params->{titleid} = $item->id();
2340     }
2341
2342     # Check for a duplicate hold:
2343     my $duplicate = $U->simplereq(
2344         'open-ils.pcrud',
2345         'open-ils.pcrud.search.ahr',
2346         $self->{session}->{authtoken},
2347         {
2348             hold_type => $hold->hold_type(),
2349             target => $hold->target(),
2350             usr => $hold->usr(),
2351             expire_time => {'>' => 'now'},
2352             cancel_time => undef,
2353             fulfillment_time => undef
2354         }
2355     );
2356     if ($duplicate) {
2357         return NCIP::Problem->new(
2358             {
2359                 ProblemType => 'Duplicate Request',
2360                 ProblemDetail => 'A request for this item already exists for this patron.',
2361                 ProblemElement => 'NULL',
2362                 ProblemValue => 'NULL'
2363             }
2364         );
2365     }
2366
2367     # Check if the hold is possible:
2368     my $r = $U->simplereq(
2369         'open-ils.circ',
2370         'open-ils.circ.title_hold.is_possible',
2371         $self->{session}->{authtoken},
2372         $params
2373     );
2374
2375     if ($r->{success}) {
2376         $hold = $U->simplereq(
2377             'open-ils.circ',
2378             'open-ils.circ.holds.create.override',
2379             $self->{session}->{authtoken},
2380             $hold
2381         );
2382         if (ref($hold)) {
2383             $hold = $hold->[0] if (ref($hold) eq 'ARRAY');
2384             $hold = _problem_from_event('Request Not Possible', $hold);
2385         } else {
2386             # open-ils.circ.holds.create.override returns the id on
2387             # success, so we retrieve the full hold object from the
2388             # database to return it.
2389             $hold = $U->simplereq(
2390                 'open-ils.pcrud',
2391                 'open-ils.pcrud.retrieve.ahr',
2392                 $self->{session}->{authtoken},
2393                 $hold
2394             );
2395         }
2396     } elsif ($r->{last_event}) {
2397         $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2398     } elsif ($r->{textcode}) {
2399         $hold = _problem_from_event('Request Not Possible', $r);
2400     } else {
2401         $hold = _problem_from_event('Request Not Possible');
2402     }
2403
2404     return $hold;
2405 }
2406
2407 =head2 cancel_hold
2408
2409     $ils->cancel_hold($hold);
2410
2411 This method cancels the hold argument. It makes no checks on the hold,
2412 so if there are certain conditions that need to be fulfilled before
2413 the hold is canceled, then you must check them before calling this
2414 method.
2415
2416 It returns undef on success or failure. If it fails, you've usually
2417 got bigger problems.
2418
2419 =cut
2420
2421 sub cancel_hold {
2422     my $self = shift;
2423     my $hold = shift;
2424
2425     my $r = $U->simplereq(
2426         'open-ils.circ',
2427         'open-ils.circ.hold.cancel',
2428         $self->{session}->{authtoken},
2429         $hold->id(),
2430         '5',
2431         'Canceled via NCIPServer'
2432     );
2433
2434     return undef;
2435 }
2436
2437 =head2 delete_copy
2438
2439     $ils->delete_copy($copy);
2440
2441 Deletes the copy, and if it is owned by our work_ou and not a precat,
2442 we also delete the volume and bib on which the copy depends.
2443
2444 =cut
2445
2446 sub delete_copy {
2447     my $self = shift;
2448     my $copy = shift;
2449
2450     # Shortcut for ownership checks below.
2451     my $ou_id = $self->{session}->{work_ou}->id();
2452
2453     # First, make sure the copy is not already deleted and we own it.
2454     return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2455
2456     # Indicate we want to delete the copy.
2457     $copy->isdeleted(1);
2458
2459     # Delete the copy using a backend call that will delete the copy,
2460     # the call number, and bib when appropriate.
2461     my $result = $U->simplereq(
2462         'open-ils.cat',
2463         'open-ils.cat.asset.copy.fleshed.batch.update.override',
2464         $self->{session}->{authtoken},
2465         [$copy]
2466     );
2467
2468     # We are currently not checking for succes or failure of the
2469     # above. At some point, someone may want to.
2470
2471     return undef;
2472 }
2473
2474 =head2 copy_can_circulate
2475
2476     $can_circulate = $ils->copy_can_circulate($copy);
2477
2478 Check if the copy's location and the copy itself allow
2479 circulation. Return true if they do, and false if they do not.
2480
2481 =cut
2482
2483 sub copy_can_circulate {
2484     my $self = shift;
2485     my $copy = shift;
2486
2487     my $location = $copy->location();
2488     unless (ref($location)) {
2489         $location = $self->retrieve_copy_location($location);
2490     }
2491
2492     return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2493 }
2494
2495 =head2 copy_can_fulfill
2496
2497     $can_fulfill = $ils->copy_can_fulfill($copy);
2498
2499 Check if the copy's location and the copy itself allow
2500 holds. Return true if they do, and false if they do not.
2501
2502 =cut
2503
2504 sub copy_can_fulfill {
2505     my $self = shift;
2506     my $copy = shift;
2507
2508     my $location = $copy->location();
2509     unless (ref($location)) {
2510         $location = $self->retrieve_copy_location($location);
2511     }
2512
2513     return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2514 }
2515
2516 =head1 OVERRIDDEN PARENT METHODS
2517
2518 =head2 find_user_barcode
2519
2520 We dangerously override our parent's C<find_user_barcode> to return
2521 either the $barcode or a Problem object. In list context the barcode
2522 or problem will be the first argument and the id field, if any, will
2523 be the second. We also add a second, optional, argument to indicate a
2524 default value for the id field in the event of a failure to find
2525 anything at all. (Perl lets us get away with this.)
2526
2527 =cut
2528
2529 sub find_user_barcode {
2530     my $self = shift;
2531     my $request = shift;
2532     my $default = shift;
2533
2534     unless ($default) {
2535         my $message = $self->parse_request_type($request);
2536         if ($message eq 'LookupUser') {
2537             $default = 'AuthenticationInputData';
2538         } else {
2539             $default = 'UserIdentifierValue';
2540         }
2541     }
2542
2543     my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2544
2545     unless ($value) {
2546         $idfield = $default unless ($idfield);
2547         $value = NCIP::Problem->new();
2548         $value->ProblemType('Needed Data Missing');
2549         $value->ProblemDetail('Cannot find user barcode in message.');
2550         $value->ProblemElement($idfield);
2551         $value->ProblemValue('NULL');
2552     }
2553
2554     return (wantarray) ? ($value, $idfield) : $value;
2555 }
2556
2557 =head2 find_item_barcode
2558
2559 We do pretty much the same thing as with C<find_user_barcode> for
2560 C<find_item_barcode>.
2561
2562 =cut
2563
2564 sub find_item_barcode {
2565     my $self = shift;
2566     my $request = shift;
2567     my $default = shift || 'ItemIdentifierValue';
2568
2569     my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2570
2571     unless ($value) {
2572         $idfield = $default unless ($idfield);
2573         $value = NCIP::Problem->new();
2574         $value->ProblemType('Needed Data Missing');
2575         $value->ProblemDetail('Cannot find item barcode in message.');
2576         $value->ProblemElement($idfield);
2577         $value->ProblemValue('NULL');
2578     }
2579
2580     return (wantarray) ? ($value, $idfield) : $value;
2581 }
2582
2583 =head2 find_target_via_bibliographic_id
2584
2585     $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2586
2587 Searches for a bibliographic record to put on hold and returns an
2588 appropriate hold target item depending upon what it finds. If an
2589 appropriate, single target cannot be found, it returns an
2590 NCIP::Problem with the problem message.
2591
2592 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2593 identifiers. If nothing is found, this method can return undef. (Gotta
2594 love Perl and untyped/weakly typed languages in general!)
2595
2596 TODO: Figure out how to search OCLC numbers. We probably need to use
2597 "MARC Expert Search" if we don't want to do a JSON query on
2598 metabib.full_rec.
2599
2600 =cut
2601
2602 sub find_target_via_bibliographic_id {
2603     my $self = shift;
2604     my @biblio_ids = @_;
2605
2606     # The item that we find:
2607     my $item;
2608
2609     # Id for our bib in Evergreen:
2610     my $bibid;
2611
2612     # First, let's look for a SYSNUMBER:
2613     my ($idobj) = grep
2614         { ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'SYSNUMBER')
2615               || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER')
2616               || $_->{AgencyId} }
2617             @biblio_ids;
2618     if ($idobj) {
2619         my $loc;
2620         # BibliographicRecordId can have an AgencyId field if the
2621         # BibliographicRecordIdentifierCode is absent.
2622         if ($idobj->{AgencyId}) {
2623             $bibid = $idobj->{BibliographicRecordIdentifier};
2624             my $locname = $idobj->{AgencyId};
2625             if ($locname) {
2626                 $locname =~ s/.*://;
2627                 $loc = $self->retrieve_org_unit_by_shortname($locname);
2628             }
2629         } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2630             $bibid = $idobj->{BibliographicRecordIdentifierCode}
2631         } else {
2632             $bibid = $idobj->{BibliographicItemIdentifierCode}
2633         }
2634         if ($bibid && $loc) {
2635             $item = $self->_call_number_search($bibid, $loc);
2636         } else {
2637             $item = $U->simplereq(
2638                 'open-ils.pcrud',
2639                 'open-ils.pcrud.retrieve.bre',
2640                 $self->{session}->{authtoken},
2641                 $bibid
2642             );
2643         }
2644         # Check if item is deleted so we'll look for more
2645         # possibilties.
2646         undef($item) if ($item && $U->is_true($item->deleted()));
2647     }
2648
2649     # Build an array of id objects based on the other identifier fields.
2650     my @idobjs = grep
2651         {
2652             ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISBN')
2653                 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISBN')
2654                 || ($_->{BibliographicRecordIdentifierCode} && $_->{BibliographicRecordIdentifierCode} eq 'ISSN')
2655                 || ($_->{BibliographicItemIdentifierCode} && $_->{BibliographicItemIdentifierCode} eq 'ISSN')
2656         } @biblio_ids;
2657
2658     if (@idobjs) {
2659         my $stashed_problem;
2660         # Reuse $idobj from above.
2661         foreach $idobj (@idobjs) {
2662             my ($idvalue, $idtype, $idfield);
2663             if ($_->{BibliographicItemIdentifier}) {
2664                 $idvalue = $_->{BibliographicItemIdentifier};
2665                 $idtype = $_->{BibliographicItemIdentifierCode};
2666                 $idfield = 'BibliographicItemIdentifier';
2667             } else {
2668                 $idvalue = $_->{BibliographicRecordIdentifier};
2669                 $idtype = $_->{BibliographicRecordIdentifierCode};
2670                 $idfield = 'BibliographicRecordIdentifier';
2671             }
2672             $item = $self->_bib_search($idvalue, $idtype);
2673             if (ref($item) eq 'NCIP::Problem') {
2674                 $stashed_problem = $item unless($stashed_problem);
2675                 $stashed_problem->ProblemElement($idfield);
2676                 undef($item);
2677             }
2678             last if ($item);
2679         }
2680         $item = $stashed_problem if (!$item && $stashed_problem);
2681     }
2682
2683     return $item;
2684 }
2685
2686 # private subroutines not meant to be used directly by subclasses.
2687 # Most have to do with setup and/or state checking of implementation
2688 # components.
2689
2690 # Find, load, and parse our configuration file:
2691 sub _configure {
2692     my $self = shift;
2693
2694     # Find the configuration file via variables:
2695     my $file = OILS_NCIP_CONFIG_DEFAULT;
2696     $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2697
2698     $self->{config} = XMLin($file, NormaliseSpace => 2,
2699                             ForceArray => ['block_profile', 'stat_cat_entry']);
2700 }
2701
2702 # Bootstrap OpenSRF::System and load the IDL.
2703 sub _bootstrap {
2704     my $self = shift;
2705
2706     my $bootstrap_config = $self->{config}->{bootstrap};
2707     OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2708
2709     my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2710     Fieldmapper->import(IDL => $idl);
2711 }
2712
2713 # Login and then initialize some object data based on the
2714 # configuration.
2715 sub _init {
2716     my $self = shift;
2717
2718     # Login to Evergreen.
2719     $self->login();
2720
2721     # Load the barred groups as pgt objects into a blocked_profiles
2722     # list.
2723     $self->{blocked_profiles} = [];
2724     foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2725         my $pgt;
2726         if (ref $_) {
2727             $pgt = $U->simplereq(
2728                 'open-ils.pcrud',
2729                 'open-ils.pcrud.retrieve.pgt',
2730                 $self->{session}->{authtoken},
2731                 $_->{grp}
2732             );
2733         } else {
2734             $pgt = $U->simplereq(
2735                 'open-ils.pcrud',
2736                 'open-ils.pcrud.search.pgt',
2737                 $self->{session}->{authtoken},
2738                 {name => $_}
2739             );
2740         }
2741         push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2742     }
2743
2744     # Load the bib source if we're not using precats.
2745     unless ($self->{config}->{items}->{use_precats}) {
2746         # Retrieve the default
2747         $self->{bib_source} = $U->simplereq(
2748             'open-ils.pcrud',
2749             'open-ils.pcrud.retrieve.cbs',
2750             $self->{session}->{authtoken},
2751             BIB_SOURCE_DEFAULT);
2752         my $data = $self->{config}->{items}->{bib_source};
2753         if ($data) {
2754             $data = $data->[0] if (ref($data) eq 'ARRAY');
2755             my $result;
2756             if (ref $data) {
2757                 $result = $U->simplereq(
2758                     'open-ils.pcrud',
2759                     'open-ils.pcrud.retrieve.cbs',
2760                     $self->{session}->{authtoken},
2761                     $data->{cbs}
2762                 );
2763             } else {
2764                 $result = $U->simplereq(
2765                     'open-ils.pcrud',
2766                     'open-ils.pcrud.search.cbs',
2767                     $self->{session}->{authtoken},
2768                     {source => $data}
2769                 );
2770             }
2771             $self->{bib_source} = $result if ($result);
2772         }
2773     }
2774
2775     # Load the required asset.stat_cat_entries:
2776     $self->{stat_cat_entries} = [];
2777     # First, make a regex for our ou and ancestors:
2778     my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2779     my $re = qr/(?:$ancestors)/;
2780     # Get the uniq stat_cat ids from the configuration:
2781     my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2782     # Retrieve all of the fleshed stat_cats and entries for the above.
2783     my $stat_cats = $U->simplereq(
2784         'open-ils.circ',
2785         'open-ils.circ.stat_cat.asset.retrieve.batch',
2786         $self->{session}->{authtoken},
2787         @cats
2788     );
2789     foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2790         # Must have the stat_cat attr and the name, so we must have a
2791         # reference.
2792         next unless(ref $entry);
2793         my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2794         push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2795     }
2796 }
2797
2798 # Search asset.call_number by a bre.id and location object. Return the
2799 # "closest" call_number if found, undef otherwise.
2800 sub _call_number_search {
2801     my $self = shift;
2802     my $bibid = shift;
2803     my $location = shift;
2804
2805     # At some point, this should be smarter, and we should retrieve
2806     # ancestors and descendants and search with a JSON query or some
2807     # such with results ordered by proximity to the original location,
2808     # but I don't have time to implement that right now.
2809     my $acn = $U->simplereq(
2810         'open-ils.pcrud',
2811         'open-ils.pcrud.search.acn',
2812         $self->{session}->{authtoken},
2813         {record => $bibid, owning_lib => $location->id()}
2814     );
2815
2816     return $acn;
2817 }
2818
2819 # Do a multiclass.query to search for items by isbn or issn.
2820 sub _bib_search {
2821     my $self = shift;
2822     my $idvalue = shift;
2823     my $idtype = shift;
2824     my $item;
2825
2826     my $result = $U->simplereq(
2827         'open-ils.search',
2828         'open-ils.search.biblio.multiclass',
2829         {searches => {lc($idtype) => $idvalue}}
2830     );
2831
2832     if ($result && $result->{count}) {
2833         if ($result->{count} > 1) {
2834             $item = NCIP::Problem->new(
2835                 {
2836                     ProblemType => 'Non-Unique Item',
2837                     ProblemDetail => 'More than one item matches the request.',
2838                     ProblemElement => '',
2839                     ProblemValue => $idvalue
2840                 }
2841             );
2842         }
2843         my $bibid = $result->{ids}->[0]->[0];
2844         $item = $U->simplereq(
2845             'open-ils.pcrud',
2846             'open-ils.pcrud.retrieve.bre',
2847             $self->{session}->{authtoken},
2848             $bibid
2849         );
2850     }
2851
2852     return $item;
2853 }
2854
2855 # Search for holds using the user and copy_details information:
2856 sub _hold_search {
2857     my $self = shift;
2858     my $user = shift;
2859     my $copy_details = shift;
2860
2861     my $hold;
2862
2863     # Retrieve all of the user's active holds, and then search them in Perl.
2864     my $holds_list = $U->simplereq(
2865         'open-ils.circ',
2866         'open-ils.circ.holds.retrieve',
2867         $self->{session}->{authtoken},
2868         $user->id(),
2869         0
2870     );
2871
2872     if ($holds_list && @$holds_list) {
2873         my @holds;
2874         # Look for title holds (the most common), first:
2875         my $targetid = $copy_details->{mvr}->doc_id();
2876         @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2877         unless (@holds) {
2878             # Look for volume holds, the next most common:
2879             $targetid = $copy_details->{volume}->id();
2880             @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2881         }
2882         unless (@holds) {
2883             # Look for copy and force holds, the least likely.
2884             $targetid = $copy_details->{copy}->id();
2885             @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
2886         }
2887         # There should only be 1, at this point, if there are any.
2888         if (@holds) {
2889             $hold = $holds[0];
2890         }
2891     }
2892
2893     return $hold;
2894 }
2895
2896 # Standalone, "helper" functions.  These do not take an object or
2897 # class reference.
2898
2899 # Check if a user is past their expiration date.
2900 sub _expired {
2901     my $user = shift;
2902     my $expired = 0;
2903
2904     # Users might not expire.  If so, they have no expire_date.
2905     if ($user->expire_date()) {
2906         my $expires = DateTime::Format::ISO8601->parse_datetime(
2907             cleanse_ISO8601($user->expire_date())
2908         )->epoch();
2909         my $now = DateTime->now()->epoch();
2910         $expired = $now > $expires;
2911     }
2912
2913     return $expired;
2914 }
2915
2916 # Creates a NCIP Problem from an event. Takes a string for the problem
2917 # type, the event hashref (or a string to use for the detail), and
2918 # optional arguments for the ProblemElement and ProblemValue fields.
2919 sub _problem_from_event {
2920     my ($type, $evt, $element, $value) = @_;
2921
2922     my $detail;
2923
2924     # Check the event.
2925     if (ref($evt)) {
2926         my ($textcode, $desc);
2927
2928         # Get the textcode, if available. Otherwise, use the ilsevent
2929         # "id," if available.
2930         if ($evt->{textcode}) {
2931             $textcode = $evt->{textcode};
2932         } elsif ($evt->{ilsevent}) {
2933             $textcode = $evt->{ilsevent};
2934         }
2935
2936         # Get the description. We favor translated descriptions over
2937         # the English in ils_events.xml.
2938         if ($evt->{desc}) {
2939             $desc = $evt->{desc};
2940         }
2941
2942         # Check if $type was set. As an "undocumented" feature, you
2943         # can pass undef, and we'll use the textcode from the event.
2944         unless ($type) {
2945             if ($textcode) {
2946                 $type = $textcode;
2947             }
2948         }
2949
2950         # Set the detail from some combination of the above.
2951         if ($desc) {
2952             $detail = $desc;
2953         } elsif ($textcode eq 'PERM_FAILURE') {
2954             if ($evt->{ilsperm}) {
2955                 $detail = "Permission denied: " . $evt->{ilsperm};
2956                 $detail =~ s/\.override$//;
2957             }
2958         } elsif ($textcode) {
2959             $detail = "ILS returned $textcode error.";
2960         } else {
2961             $detail = 'Detail not available.';
2962         }
2963
2964     } else {
2965         $detail = $evt;
2966     }
2967
2968     return NCIP::Problem->new(
2969         {
2970             ProblemType => ($type) ? $type : 'Temporary Processing Failure',
2971             ProblemDetail => ($detail) ? $detail : 'Detail not available.',
2972             ProblemElement => ($element) ? $element : 'NULL',
2973             ProblemValue => ($value) ? $value : 'NULL'
2974         }
2975     );
2976 }
2977
2978 # "Fix" dates for output so they validate against the schema
2979 sub _fix_date {
2980     my $date = shift;
2981     my $out = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($date));
2982     $out->set_time_zone('UTC');
2983     return $out->iso8601();
2984 }
2985
2986 1;