]> git.evergreen-ils.org Git - working/NCIPServer.git/blob - lib/NCIP/ILS/Evergreen.pm
Add handling of ItemElementType in NIP::ILS::Evergreen.
[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 => $copy,
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         my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
678         $due->set_time_zone('UTC');
679         $data->{DateDue} = $due->iso8601();
680
681         # Look for UserElements requested and add it to the response:
682         my $elements = $request->{$message}->{UserElementType};
683         if ($elements) {
684             $elements = [$elements] unless (ref $elements eq 'ARRAY');
685             my $optionalfields = $self->handle_user_elements($user, $elements);
686             $data->{UserOptionalFields} = $optionalfields;
687         }
688         $elements = $request->{$message}->{ItemElementType};
689         if ($elements) {
690             $elements = [$elements] unless (ref $elements eq 'ARRAY');
691             my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
692             $data->{ItemOptionalFields} = $optionalfields;
693         }
694
695         $response->data($data);
696     }
697
698     # At some point in the future, we should probably check if
699     # they requested optional user or item elements and return
700     # those. For the time being, we ignore those at the risk of
701     # being considered non-compliant.
702
703     return $response;
704 }
705
706 =head2 checkoutitem
707
708     $response = $ils->checkoutitem($request);
709
710 Handle the Checkoutitem message.
711
712 =cut
713
714 sub checkoutitem {
715     my $self = shift;
716     my $request = shift;
717
718     # Check our session and login if necessary:
719     $self->login() unless ($self->checkauth());
720
721     # Common stuff:
722     my $message = $self->parse_request_type($request);
723     my $response = NCIP::Response->new({type => $message . 'Response'});
724     $response->header($self->make_header($request));
725
726     # We need the copy barcode from the message.
727     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
728     if (ref($item_barcode) eq 'NCIP::Problem') {
729         $response->problem($item_barcode);
730         return $response;
731     }
732
733     # Retrieve the copy details.
734     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
735     unless ($details) {
736         # Return an Unknown Item problem unless we find the copy.
737         $response->problem(
738             NCIP::Problem->new(
739                 {
740                     ProblemType => 'Unknown Item',
741                     ProblemDetail => "Item with barcode $item_barcode is not known.",
742                     ProblemElement => $item_idfield,
743                     ProblemValue => $item_barcode
744                 }
745             )
746         );
747         return $response;
748     }
749
750     # User is required for CheckOutItem.
751     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
752     if (ref($user_barcode) eq 'NCIP::Problem') {
753         $response->problem($user_barcode);
754         return $response;
755     }
756     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
757     if (ref($user) eq 'NCIP::Problem') {
758         $response->problem($user);
759         return $response;
760     }
761
762     # Isolate the copy.
763     my $copy = $details->{copy};
764
765     # Check if the copy can circulate.
766     unless ($self->copy_can_circulate($copy)) {
767         $response->problem(
768             NCIP::Problem->new(
769                 {
770                     ProblemType => 'Item Does Not Circulate',
771                     ProblemDetail => "Item with barcode $item_barcode does not circulate.",
772                     ProblemElement => $item_idfield,
773                     ProblemValue => $item_barcode
774                 }
775             )
776         );
777         return $response;
778     }
779
780     # Look for a circulation and examine its information:
781     my $circ = $details->{circ};
782
783     # Check if the item is already checked out.
784     if ($circ && !$circ->checkin_time()) {
785         $response->problem(
786             NCIP::Problem->new(
787                 {
788                     ProblemType => 'Item Already Checked Out',
789                     ProblemDetail => "Item with barcode $item_barcode is already checked out.",
790                     ProblemElement => $item_idfield,
791                     ProblemValue => $item_barcode
792                 }
793             )
794         );
795         return $response;
796     }
797
798     # Check if user is blocked from circulation:
799     my $problem = $self->check_user_for_problems($user, 'CIRC');
800     if ($problem) {
801         # Replace the ProblemElement and ProblemValue fields.
802         $problem->ProblemElement($user_idfield);
803         $problem->ProblemValue($user_barcode);
804         $response->problem($problem);
805         return $response;
806     }
807
808     # Now, we attempt the check out. If it fails, we simply say that
809     # the user is not allowed to check out this item, without getting
810     # into details.
811     my $params = {
812         copy => $copy,
813         patron_id => $user->id(),
814     };
815     my $r = $U->simplereq(
816         'open-ils.circ',
817         'open-ils.circ.checkout.full.override',
818         $self->{session}->{authtoken},
819         $params
820     );
821
822     # We only look at the first one, since more than one usually means
823     # failure.
824     if (ref($r) eq 'ARRAY') {
825         $r = $r->[0];
826     }
827     if ($r->{textcode} ne 'SUCCESS') {
828         $problem = _problem_from_event('Check Out Failed', $r);
829         $response->problem($problem);
830     } else {
831         my $data = {
832             ItemId => NCIP::Item::Id->new(
833                 {
834                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
835                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
836                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
837                 }
838             ),
839             UserId => NCIP::User::Id->new(
840                 {
841                     UserIdentifierType => 'Barcode Id',
842                     UserIdentifierValue => $user->card->barcode()
843                 }
844             )
845         };
846         # We need to retrieve the copy details again to refresh our
847         # circ information to get the due date.
848         $details = $self->retrieve_copy_details_by_barcode($item_barcode);
849         $circ = $details->{circ};
850         my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
851         $due->set_time_zone('UTC');
852         $data->{DateDue} = $due->iso8601();
853
854         # Look for UserElements requested and add it to the response:
855         my $elements = $request->{$message}->{UserElementType};
856         if ($elements) {
857             $elements = [$elements] unless (ref $elements eq 'ARRAY');
858             my $optionalfields = $self->handle_user_elements($user, $elements);
859             $data->{UserOptionalFields} = $optionalfields;
860         }
861         $elements = $request->{$message}->{ItemElementType};
862         if ($elements) {
863             $elements = [$elements] unless (ref $elements eq 'ARRAY');
864             my $optionalfields = $self->handle_item_elements($details->{copy}, $elements);
865             $data->{ItemOptionalFields} = $optionalfields;
866         }
867
868         $response->data($data);
869     }
870
871     # At some point in the future, we should probably check if
872     # they requested optional user or item elements and return
873     # those. For the time being, we ignore those at the risk of
874     # being considered non-compliant.
875
876     return $response;
877 }
878
879 =head2 requestitem
880
881     $response = $ils->requestitem($request);
882
883 Handle the NCIP RequestItem message.
884
885 =cut
886
887 sub requestitem {
888     my $self = shift;
889     my $request = shift;
890     # Check our session and login if necessary:
891     $self->login() unless ($self->checkauth());
892
893     # Common stuff:
894     my $message = $self->parse_request_type($request);
895     my $response = NCIP::Response->new({type => $message . 'Response'});
896     $response->header($self->make_header($request));
897
898     # Because we need to have a user to place a hold, because the user
899     # is likely to have problems, and because getting the item
900     # information for the hold is trickier than getting the user
901     # information, we'll do the user first and short circuit out of
902     # the function if there is a problem with the user.
903     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
904     if (ref($user_barcode) eq 'NCIP::Problem') {
905         $response->problem($user_barcode);
906         return $response;
907     }
908     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
909     if (ref($user) eq 'NCIP::Problem') {
910         $response->problem($user);
911         return $response;
912     }
913     my $problem = $self->check_user_for_problems($user, 'HOLD');
914     if ($problem) {
915         $response->problem($problem);
916         return $response;
917     }
918
919     # RequestItem is a blast. We need to check if we have a copy
920     # barcode and/or if we have BibliographicIds. If we have both or
921     # either, we then need to figure out what we're placing the hold
922     # on, a copy, a volume or a bib. We don't currently do part holds,
923     # but maybe we should some day. We can also be sent more than 1
924     # BibliographicId, so we look for certain identifiers first, and
925     # then others in decreasing preference: SYSNUMBER, ISBN, and ISSN.
926
927     # Not to mention that there are two kinds of BibliographicId field
928     # with different field names, and both can be intermixed in an
929     # incoming message! (I just /love/ this nonsense.)
930
931     # This here is the thing we're going to put on hold:
932     my $item;
933
934     # We need the copy barcode from the message.
935     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
936     if (ref($item_barcode) ne 'NCIP::Problem') {
937         # Retrieve the copy details.
938         my $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
939         unless ($copy_details) {
940             # Return an Unknown Item problem unless we find the copy.
941             $response->problem(
942                 NCIP::Problem->new(
943                     {
944                         ProblemType => 'Unknown Item',
945                         ProblemDetail => "Item with barcode $item_barcode is not known.",
946                         ProblemElement => $item_idfield,
947                         ProblemValue => $item_barcode
948                     }
949                 )
950             );
951             return $response;
952         }
953         $item = $copy_details->{volume}; # We place a volume hold.
954     }
955
956     # We weren't given copy information to target, or we can't find
957     # it, so we need to look for a target via BibliographicId.
958     unless ($item) {
959         my @biblio_ids = $self->find_bibliographic_ids($request);
960         if (@biblio_ids) {
961             $item = $self->find_target_via_bibliographic_id(@biblio_ids);
962         }
963     }
964
965     # If we don't have an item, then blow up with a problem that may
966     # have been set when we went looking for the ItemId.
967     unless ($item) {
968         if (ref($item_barcode) eq 'NCIP::Problem') {
969             $response->problem($item_barcode);
970         } else {
971             $response->problem(
972                 NCIP::Problem->new(
973                     {
974                         ProblemType => 'Request Item Not Found',
975                         ProblemDetail => 'Unable to determine the item to request from input message.',
976                         ProblemElement => 'NULL',
977                         ProblemValue => 'NULL'
978                     }
979                 )
980             );
981         }
982         return $response;
983     } elsif (ref($item) eq 'NCIP::Problem') {
984         $response->problem($item);
985         return $response;
986     }
987
988     # See if we were given a PickupLocation.
989     my $location;
990     if ($request->{$message}->{PickupLocation}) {
991         my $loc = $request->{$message}->{PickupLocation};
992         $loc =~ s/^.*://; # strip everything up to the last
993                           # semi-colon, if any.
994         $location = $self->retrieve_org_unit_by_shortname($loc);
995     }
996
997     # Look for a NeedBeforeDate to use as expiration...
998     my $hold_expiration = $request->{$message}->{NeedBeforeDate};
999
1000     # Place the hold.
1001     my $hold = $self->place_hold($item, $user, $location, $hold_expiration);
1002     if (ref($hold) eq 'NCIP::Problem') {
1003         $response->problem($hold);
1004     } else {
1005         my $data = {
1006             RequestId => NCIP::RequestId->new(
1007                 RequestIdentifierType => 'SYSNUMBER',
1008                 RequestIdentifierValue => $hold->id()
1009             ),
1010             UserId => NCIP::User::Id->new(
1011                 {
1012                     UserIdentifierType => 'Barcode Id',
1013                     UserIdentifierValue => $user->card->barcode()
1014                 }
1015             ),
1016             RequestType => $request->{$message}->{RequestType},
1017             RequestScopeType => ($hold->hold_type() eq 'V') ? "item" : "bibliographic item"
1018         };
1019         # Look for UserElements requested and add it to the response:
1020         my $elements = $request->{$message}->{UserElementType};
1021         if ($elements) {
1022             $elements = [$elements] unless (ref $elements eq 'ARRAY');
1023             my $optionalfields = $self->handle_user_elements($user, $elements);
1024             $data->{UserOptionalFields} = $optionalfields;
1025         }
1026         $elements = $request->{$message}->{ItemElementType};
1027         if ($elements && $copy_details) {
1028             $elements = [$elements] unless (ref($elements) eq 'ARRAY');
1029             my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1030             $data->{ItemOptionalFields} = $optionalfields;
1031         }
1032
1033         $response->data($data);
1034     }
1035
1036     return $response;
1037 }
1038
1039 =head2 cancelrequestitem
1040
1041     $response = $ils->cancelrequestitem($request);
1042
1043 Handle the NCIP CancelRequestItem message.
1044
1045 =cut
1046
1047 sub cancelrequestitem {
1048     my $self = shift;
1049     my $request = shift;
1050     # Check our session and login if necessary:
1051     $self->login() unless ($self->checkauth());
1052
1053     # Common stuff:
1054     my $message = $self->parse_request_type($request);
1055     my $response = NCIP::Response->new({type => $message . 'Response'});
1056     $response->header($self->make_header($request));
1057
1058     # UserId is required by the standard, but we might not really need it.
1059     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
1060     if (ref($user_barcode) eq 'NCIP::Problem') {
1061         $response->problem($user_barcode);
1062         return $response;
1063     }
1064     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
1065     if (ref($user) eq 'NCIP::Problem') {
1066         $response->problem($user);
1067         return $response;
1068     }
1069
1070     # See if we got a ItemId and a barcode:
1071     my $copy_details;
1072     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
1073     if (ref($item_barcode) ne 'NCIP::Problem') {
1074         # Retrieve the copy details.
1075         $copy_details = $self->retrieve_copy_details_by_barcode($item_barcode);
1076         unless ($copy_details) {
1077             # Return an Unknown Item problem unless we find the copy.
1078             $response->problem(
1079                 NCIP::Problem->new(
1080                     {
1081                         ProblemType => 'Unknown Item',
1082                         ProblemDetail => "Item with barcode $item_barcode is not known.",
1083                         ProblemElement => $item_idfield,
1084                         ProblemValue => $item_barcode
1085                     }
1086                 )
1087             );
1088             return $response;
1089         }
1090     }
1091
1092     # See if we got a RequestId:
1093     my $requestid;
1094     if ($request->{$message}->{RequestId}) {
1095         $requestid = NCIP::RequestId->new(
1096             {
1097                 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
1098                 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
1099                 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
1100             }
1101         )
1102     }
1103
1104     # Just a note: In the below, we cannot rely on the hold or transit
1105     # fields of the copy_details, even if we have retrieved it. This
1106     # is because that hold and transit may not be the ones that we're
1107     # looking for, i.e. they could be for another patron, etc.
1108
1109     # See if we can find the hold:
1110     my $hold;
1111     if ($requestid) {
1112         $hold = $U->simplereq(
1113             'open-ils.pcrud',
1114             'open-ils.pcrud.retrieve.ahr',
1115             $self->{session}->{authtoken},
1116             $requestid->{RequestIdentifierValue},
1117             {flesh => 1, flesh_fields => {ahr => ['transit']}}
1118         );
1119         unless ($hold) {
1120             # Report a problem that we couldn't find a hold by that id.
1121             $response->problem(
1122                 NCIP::Problem->new(
1123                     {
1124                         ProblemType => 'Unknown Request',
1125                         ProblemDetail => 'No request with this identifier found',
1126                         ProblemElement => 'RequestIdentifierValue',
1127                         ProblemValue => $requestid->{RequestIdentifierValue}
1128                     }
1129                 )
1130             )
1131         } elsif ($hold->cancel_time()) {
1132             $response->problem(
1133                 NCIP::Problem->new(
1134                     {
1135                         ProblemType => 'Request Already Canceled',
1136                         ProblemDetail => 'Request has already been canceled',
1137                         ProblemElement => 'RequestIdentifierValue',
1138                         ProblemValue => $requestid->{RequestIdentifierValue}
1139                     }
1140                 )
1141             )
1142         } elsif ($hold->transit()) {
1143             $response->problem(
1144                 NCIP::Problem->new(
1145                     {
1146                         ProblemType => 'Request Already Processed',
1147                         ProblemDetail => 'Request has already been processed',
1148                         ProblemElement => 'RequestIdentifierValue',
1149                         ProblemValue => $requestid->{RequestIdentifierValue}
1150                     }
1151                 )
1152             )
1153         } elsif ($hold->usr() == $user->id()) {
1154             # Check the target matches the copy information, if any,
1155             # that we were given.
1156             my $obj_id;
1157             if ($copy_details) {
1158                 if ($hold->hold_type() eq 'V') {
1159                     $obj_id = $copy_details->{volume}->id();
1160                 } elsif ($hold->hold_type() eq 'T') {
1161                     $obj_id = $copy_details->{mvr}->doc_id();
1162                 } elsif ($hold->hold_type() eq 'C' || $hold->hold_type() eq 'F') {
1163                     $obj_id = $copy_details->{copy}->id();
1164                 }
1165             }
1166             if ($obj_id && $hold->target() != $obj_id) {
1167                 $response->problem(
1168                     NCIP::Problem->new(
1169                         {
1170                             ProblemType => 'Request Not For This Item',
1171                             ProblemDetail => "Request is not for this item",
1172                             ProblemElement => $item_idfield,
1173                             ProblemElement => $item_barcode
1174                         }
1175                     )
1176                 )
1177             } else {
1178                 $self->cancel_hold($hold);
1179                 my $data = {
1180                     RequestId => $requestid,
1181                     UserId => NCIP::User::Id->new(
1182                         {
1183                             UserIdentifierType => 'Barcode Id',
1184                             UserIdentifierValue => $user->card->barcode()
1185                         }
1186                     )
1187                 };
1188                 # Look for UserElements requested and add it to the response:
1189                 my $elements = $request->{$message}->{UserElementType};
1190                 if ($elements) {
1191                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1192                     my $optionalfields = $self->handle_user_elements($user, $elements);
1193                     $data->{UserOptionalFields} = $optionalfields;
1194                 }
1195                 $elements = $request->{$message}->{ItemElementType};
1196                 if ($elements && $copy_details) {
1197                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1198                     my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1199                     $data->{ItemOptionalFields} = $optionalfields;
1200                 }
1201                 $response->data($data);
1202             }
1203         } else {
1204             # Report a problem that the hold is not for this user.
1205             $response->problem(
1206                 NCIP::Problem->new(
1207                     {
1208                         ProblemType => 'Request Not For This User',
1209                         ProblemDetail => 'Request is not for this user.',
1210                         ProblemElement => $user_idfield,
1211                         ProblemValue => $user_barcode
1212                     }
1213                 )
1214             )
1215         }
1216     } else {
1217         # At this point, we *must have* an ItemId and therefore
1218         # $copy_details, so return the problem from looking up the
1219         # barcode if we don't have $copy_details.
1220         if (!$copy_details) {
1221             $response->problem($item_barcode);
1222         } else {
1223             # We have to search for the hold based on the copy details and
1224             # the user.  We'll need to search for copy (or force) holds, a
1225             # volume hold, or a title hold.
1226             $hold = $self->_hold_search($user, $copy_details);
1227             if ($hold && $hold->transit()) {
1228                 $response->problem(
1229                     NCIP::Problem->new(
1230                         {
1231                             ProblemType => 'Request Already Processed',
1232                             ProblemDetail => 'Request has already been processed',
1233                             ProblemElement => 'RequestIdentifierValue',
1234                             ProblemValue => $requestid->{RequestIdentifierValue}
1235                         }
1236                     )
1237                 )
1238             } elsif ($hold) {
1239                 $self->cancel_hold($hold);
1240                 my $data = {
1241                     RequestId => NCIP::RequestId->new(
1242                         {
1243                             RequestIdentifierType => 'SYSNUMBER',
1244                             RequestIdentifierValue => $hold->id()
1245                         }
1246                     ),
1247                     UserId => NCIP::User::Id->new(
1248                         {
1249                             UserIdentifierType => 'Barcode Id',
1250                             UserIdentifierValue => $user->card->barcode()
1251                         }
1252                     )
1253                 };
1254                 # Look for UserElements requested and add it to the response:
1255                 my $elements = $request->{$message}->{UserElementType};
1256                 if ($elements) {
1257                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1258                     my $optionalfields = $self->handle_user_elements($user, $elements);
1259                     $data->{UserOptionalFields} = $optionalfields;
1260                 }
1261                 $elements = $request->{$message}->{ItemElementType};
1262                 if ($elements && $copy_details) {
1263                     $elements = [$elements] unless (ref $elements eq 'ARRAY');
1264                     my $optionalfields = $self->handle_item_elements($copy_details->{copy}, $elements);
1265                     $data->{ItemOptionalFields} = $optionalfields;
1266                 }
1267                 $response->data($data);
1268             } else {
1269                 $response->problem(
1270                     NCIP::Problem->new(
1271                         {
1272                             ProblemType => 'Unknown Request',
1273                             ProblemDetail => 'No request found for the item and user',
1274                             ProblemElement => 'NULL',
1275                             ProblemValue => 'NULL'
1276                         }
1277                     )
1278                 )
1279             }
1280         }
1281     }
1282
1283     return $response;
1284 }
1285
1286 =head1 METHODS USEFUL to SUBCLASSES
1287
1288 =head2 handle_user_elements
1289     $useroptionalfield = $ils->handle_user_elements($user, $elements);
1290
1291 Returns NCIP::User::OptionalFields for the given user and arrayref of
1292 UserElement.
1293
1294 =cut
1295
1296 sub handle_user_elements {
1297     my $self = shift;
1298     my $user = shift;
1299     my $elements = shift;
1300     my $optionalfields = NCIP::User::OptionalFields->new();
1301
1302     # First, we'll look for name information.
1303     if (grep {$_ eq 'Name Information'} @$elements) {
1304         my $name = NCIP::StructuredPersonalUserName->new();
1305         $name->Surname($user->family_name());
1306         $name->GivenName($user->first_given_name());
1307         $name->Prefix($user->prefix());
1308         $name->Suffix($user->suffix());
1309         $optionalfields->NameInformation($name);
1310     }
1311
1312     # Next, check for user address information.
1313     if (grep {$_ eq 'User Address Information'} @$elements) {
1314         my $addresses = [];
1315
1316         # See if the user has any valid, physcial addresses.
1317         foreach my $addr (@{$user->addresses()}) {
1318             next if ($U->is_true($addr->pending()));
1319             my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
1320             my $physical = NCIP::StructuredAddress->new();
1321             $physical->Line1($addr->street1());
1322             $physical->Line2($addr->street2());
1323             $physical->Locality($addr->city());
1324             $physical->Region($addr->state());
1325             $physical->PostalCode($addr->post_code());
1326             $physical->Country($addr->country());
1327             $address->PhysicalAddress($physical);
1328             push @$addresses, $address;
1329         }
1330
1331         # Right now, we're only sharing email address if the user
1332         # has it. We don't share phone numbers.
1333         if ($user->email()) {
1334             my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
1335             $address->ElectronicAddress(
1336                 NCIP::ElectronicAddress->new({
1337                     Type=>'Email Address',
1338                     Data=>$user->email()
1339                 })
1340                 );
1341             push @$addresses, $address;
1342         }
1343
1344         $optionalfields->UserAddressInformation($addresses);
1345     }
1346
1347     # Check for User Privilege.
1348     if (grep {$_ eq 'User Privilege'} @$elements) {
1349         # Get the user's group:
1350         my $pgt = $U->simplereq(
1351             'open-ils.pcrud',
1352             'open-ils.pcrud.retrieve.pgt',
1353             $self->{session}->{authtoken},
1354             $user->profile()
1355         );
1356         if ($pgt) {
1357             my $privilege = NCIP::User::Privilege->new();
1358             $privilege->AgencyId($user->home_ou->shortname());
1359             $privilege->AgencyUserPrivilegeType($pgt->name());
1360             $privilege->ValidToDate($user->expire_date());
1361             $privilege->ValidFromDate($user->create_date());
1362
1363             my $status = 'Active';
1364             if (_expired($user)) {
1365                 $status = 'Expired';
1366             } elsif ($U->is_true($user->barred())) {
1367                 $status = 'Barred';
1368             } elsif (!$U->is_true($user->active())) {
1369                 $status = 'Inactive';
1370             }
1371             if ($status) {
1372                 $privilege->UserPrivilegeStatus(
1373                     NCIP::User::PrivilegeStatus->new({
1374                         UserPrivilegeStatusType => $status
1375                     })
1376                 );
1377             }
1378
1379             $optionalfields->UserPrivilege([$privilege]);
1380         }
1381     }
1382
1383     # Check for Block Or Trap.
1384     if (grep {$_ eq 'Block Or Trap'} @$elements) {
1385         my $blocks = [];
1386
1387         # First, let's check if the profile is blocked from ILL.
1388         if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1389             my $block = NCIP::User::BlockOrTrap->new();
1390             $block->AgencyId($user->home_ou->shortname());
1391             $block->BlockOrTrapType('Block Interlibrary Loan');
1392             push @$blocks, $block;
1393         }
1394
1395         # Next, we loop through the user's standing penalties
1396         # looking for blocks on CIRC, HOLD, and RENEW.
1397         my ($have_circ, $have_renew, $have_hold) = (0,0,0);
1398         foreach my $penalty (@{$user->standing_penalties()}) {
1399             next unless($penalty->standing_penalty->block_list());
1400             my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
1401             my $ou = $U->simplereq(
1402                 'open-ils.pcrud',
1403                 'open-ils.pcrud.retrieve.aou',
1404                 $self->{session}->{authtoken},
1405                 $penalty->org_unit()
1406             );
1407
1408             # Block checkout.
1409             if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
1410                 my $bot = NCIP::User::BlockOrTrap->new();
1411                 $bot->AgencyId($ou->shortname());
1412                 $bot->BlockOrTrapType('Block Checkout');
1413                 push @$blocks, $bot;
1414                 $have_circ = 1;
1415             }
1416
1417             # Block holds.
1418             if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
1419                 my $bot = NCIP::User::BlockOrTrap->new();
1420                 $bot->AgencyId($ou->shortname());
1421                 $bot->BlockOrTrapType('Block Holds');
1422                 push @$blocks, $bot;
1423                 $have_hold = 1;
1424             }
1425
1426             # Block renewals.
1427             if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
1428                 my $bot = NCIP::User::BlockOrTrap->new();
1429                 $bot->AgencyId($ou->shortname());
1430                 $bot->BlockOrTrapType('Block Renewals');
1431                 push @$blocks, $bot;
1432                 $have_renew = 1;
1433             }
1434
1435             # Stop after we report one of each, even if more
1436             # blocks remain.
1437             last if ($have_circ && $have_renew && $have_hold);
1438         }
1439
1440         $optionalfields->BlockOrTrap($blocks);
1441     }
1442
1443     return $optionalfields;
1444 }
1445
1446 =head2 handle_item_elements
1447
1448 =cut
1449
1450 sub handle_item_elements {
1451     my $self = shift;
1452     my $copy = shift;
1453     my $elments = shift;
1454     my $optionalfields = NCIP::Item::OptionalFields->new();
1455
1456     my $details; # In case we need for more than one.
1457
1458     if (grep {$_ eq 'Bibliographic Description'} @$elements) {
1459         my $description;
1460         # Check for a precat copy, 'cause it is simple.
1461         if ($copy->dummy_title()) {
1462             $description = NCIP::Item::BibliographicDescription->new();
1463             $description->Title($copy->dummy_title());
1464             $description->Author($copy->dummy_author());
1465             if ($copy->dummy_isbn()) {
1466                 $description->BibliographicItemId(
1467                     NCIP::Item::BibliographicItemId->new(
1468                         BibliographicItemIdentifier => $copy->dummy_isbn(),
1469                         BibliographicItemIdentifierCode => 'ISBN'
1470                     )
1471                 );
1472             }
1473         } else {
1474             $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1475             $description = NCIP::Item::BibliographicDescription->new();
1476             $description->Title($details->{mvr}->title());
1477             $description->Authort($details->{mvr}->author());
1478             $description->BibliographicRecordId(
1479                 NCIP::Item::BibliographicRecordId->new(
1480                     BibliographicRecordIdentifier => $details->{mvr}->doc_id(),
1481                     BibliographicRecordIdentifierCode => 'SYSNUMBER'
1482                 )
1483             );
1484             if ($details->{mvr}->publisher()) {
1485                 $description->Publisher($details->{mvr}->publisher());
1486             }
1487             if ($details->{mvr}->pubdate()) {
1488                 $description->PublicationDate($details->{mvr}->pubdate());
1489             }
1490             if ($details->{mvr}->edition()) {
1491                 $description->Edition($details->{mvr}->edition());
1492             }
1493         }
1494         $optionalfields->BibliographicDescription($description) if ($description);
1495     }
1496
1497     if (grep {$_ eq 'Item Description'} @$elements) {
1498         $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1499         # Call Number is the only field we currently return. We also
1500         # do not attempt to retun a prefix and suffix. Someone else
1501         # can deal with that if they want it.
1502         if ($details->{volume}) {
1503             $optionalfields->ItemDescription(
1504                 NCIP::Item::Description->new(
1505                     CallNumber => $details->{volume}->label();
1506                 )
1507             );
1508         }
1509     }
1510
1511     if (grep {$_ eq 'Circulation Status'} @$elements) {
1512         my $status = $copy->status();
1513         $status = $self->retrieve_copy_status($status) unless (ref($status));
1514         $optionalfields->CirculationStatus($status->name()) if ($status);
1515     }
1516
1517     if (grep {$_ eq 'Date Due'} @$elements) {
1518         $details = $self->retrieve_copy_details_by_barcode($copy->barcode()) unless($details);
1519         if ($details->{circ}) {
1520             if (!$details->{circ}->checkin_time()) {
1521                 my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
1522                 $due->set_time_zone('UTC');
1523                 $optionalfields->DateDue($due->iso8601());
1524             }
1525         }
1526     }
1527
1528     if (grep {$_ eq 'Item Use Restriction Type'} @$elements) {
1529         $optionalfields->ItemUseRestrictionType('None');
1530     }
1531
1532     if (grep {$_ eq 'Physical Condition'} @$elements) {
1533         $optionalfields->PhysicalCondition(
1534             NCIP::Item::PhysicalCondition->new(
1535                 PhysicalConditionType => 'Unknown'
1536             )
1537         );
1538     }
1539
1540     return $optionalfields;
1541 }
1542
1543 =head2 login
1544
1545     $ils->login();
1546
1547 Login to Evergreen via OpenSRF. It uses internal state from the
1548 configuration file to login.
1549
1550 =cut
1551
1552 # Login via OpenSRF to Evergreen.
1553 sub login {
1554     my $self = shift;
1555
1556     # Get the authentication seed.
1557     my $seed = $U->simplereq(
1558         'open-ils.auth',
1559         'open-ils.auth.authenticate.init',
1560         $self->{config}->{credentials}->{username}
1561     );
1562
1563     # Actually login.
1564     if ($seed) {
1565         my $response = $U->simplereq(
1566             'open-ils.auth',
1567             'open-ils.auth.authenticate.complete',
1568             {
1569                 username => $self->{config}->{credentials}->{username},
1570                 password => md5_hex(
1571                     $seed . md5_hex($self->{config}->{credentials}->{password})
1572                 ),
1573                 type => 'staff',
1574                 workstation => $self->{config}->{credentials}->{workstation}
1575             }
1576         );
1577         if ($response) {
1578             $self->{session}->{authtoken} = $response->{payload}->{authtoken};
1579             $self->{session}->{authtime} = $response->{payload}->{authtime};
1580
1581             # Set/reset the work_ou and user data in case something changed.
1582
1583             # Retrieve the work_ou as an object.
1584             $self->{session}->{work_ou} = $U->simplereq(
1585                 'open-ils.pcrud',
1586                 'open-ils.pcrud.search.aou',
1587                 $self->{session}->{authtoken},
1588                 {shortname => $self->{config}->{credentials}->{work_ou}}
1589             );
1590
1591             # We need the user information in order to do some things.
1592             $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
1593
1594         }
1595     }
1596 }
1597
1598 =head2 checkauth
1599
1600     $valid = $ils->checkauth();
1601
1602 Returns 1 if the object a 'valid' authtoken, 0 if not.
1603
1604 =cut
1605
1606 sub checkauth {
1607     my $self = shift;
1608
1609     # We use AppUtils to do the heavy lifting.
1610     if (defined($self->{session})) {
1611         if ($U->check_user_session($self->{session}->{authtoken})) {
1612             return 1;
1613         } else {
1614             return 0;
1615         }
1616     }
1617
1618     # If we reach here, we don't have a session, so we are definitely
1619     # not logged in.
1620     return 0;
1621 }
1622
1623 =head2 retrieve_user_by_barcode
1624
1625     $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
1626
1627 Do a fleshed retrieve of a patron by barcode. Return the patron if
1628 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
1629
1630 The id field argument is used for the ProblemElement field in the
1631 NCIP::Problem object.
1632
1633 An invalid patron is one where the barcode is not found in the
1634 database, the patron is deleted, or the barcode used to retrieve the
1635 patron is not active. The problem element is also returned if an error
1636 occurs during the retrieval.
1637
1638 =cut
1639
1640 sub retrieve_user_by_barcode {
1641     my ($self, $barcode, $idfield) = @_;
1642     my $result = $U->simplereq(
1643         'open-ils.actor',
1644         'open-ils.actor.user.fleshed.retrieve_by_barcode',
1645         $self->{session}->{authtoken},
1646         $barcode,
1647         1
1648     );
1649
1650     # Check for a failure, or a deleted, inactive, or expired user,
1651     # and if so, return empty userdata.
1652     if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
1653             || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
1654
1655         my $problem = NCIP::Problem->new();
1656         $problem->ProblemType('Unknown User');
1657         $problem->ProblemDetail("User with barcode $barcode unknown");
1658         $problem->ProblemElement($idfield);
1659         $problem->ProblemValue($barcode);
1660         $result = $problem;
1661     }
1662
1663     return $result;
1664 }
1665
1666 =head2 retrieve_user_by_id
1667
1668     $user = $ils->retrieve_user_by_id($id);
1669
1670 Similar to C<retrieve_user_by_barcode> but takes the user's database
1671 id rather than barcode. This is useful when you have a circulation or
1672 hold and need to get information about the user's involved in the hold
1673 or circulaiton.
1674
1675 It returns a fleshed user on success or undef on failure.
1676
1677 =cut
1678
1679 sub retrieve_user_by_id {
1680     my ($self, $id) = @_;
1681
1682     # Do a fleshed retrieve of the patron, and flesh the fields that
1683     # we would normally use.
1684     my $result = $U->simplereq(
1685         'open-ils.actor',
1686         'open-ils.actor.user.fleshed.retrieve',
1687         $self->{session}->{authtoken},
1688         $id,
1689         [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
1690     );
1691     # Check for an error.
1692     undef($result) if ($result && $U->event_code($result));
1693
1694     return $result;
1695 }
1696
1697 =head2 check_user_for_problems
1698
1699     $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
1700
1701 This function checks if a user has a blocked profile or any from a
1702 list of provided blocks. If it does, then a NCIP::Problem object is
1703 returned, otherwise an undefined value is returned.
1704
1705 The list of blocks appears as additional arguments after the user. You
1706 can provide any value(s) that might appear in a standing penalty block
1707 lit in Evergreen. The example above checks for HOLD, CIRC, and
1708 RENEW. Any number of such values can be provided. If none are
1709 provided, the function only checks if the patron's profiles appears in
1710 the object's blocked profiles list.
1711
1712 It stops on the first matching block, if any.
1713
1714 =cut
1715
1716 sub check_user_for_problems {
1717     my $self = shift;
1718     my $user = shift;
1719     my @blocks = @_;
1720
1721     # Fill this in if we have a problem, otherwise just return it.
1722     my $problem;
1723
1724     # First, check the user's profile.
1725     if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
1726         $problem = NCIP::Problem->new(
1727             {
1728                 ProblemType => 'User Blocked',
1729                 ProblemDetail => 'User blocked from inter-library loan',
1730                 ProblemElement => 'NULL',
1731                 ProblemValue => 'NULL'
1732             }
1733         );
1734     }
1735
1736     # Next, check if the patron has one of the indicated blocks.
1737     unless ($problem) {
1738         foreach my $penalty (@{$user->standing_penalties()}) {
1739             if ($penalty->standing_penalty->block_list()) {
1740                 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1741                 foreach my $block (@blocks) {
1742                     if (grep {$_ =~ /$block/} @pblocks) {
1743                         $problem = NCIP::Problem->new(
1744                             {
1745                                 ProblemType => 'User Blocked',
1746                                 ProblemDetail => 'User blocked from ' .
1747                                     ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1748                                                                         (($block eq 'CIRC') ? 'checkout' : lc($block))),
1749                                 ProblemElement => 'NULL',
1750                                 ProblemValue => 'NULL'
1751                             }
1752                         );
1753                         last;
1754                     }
1755                 }
1756                 last if ($problem);
1757             }
1758         }
1759     }
1760
1761     return $problem;
1762 }
1763
1764 =head2 check_circ_details
1765
1766     $problem = $ils->check_circ_details($circ, $copy, $user);
1767
1768 Checks if we can checkin or renew a circulation. That is, the
1769 circulation is still open (i.e. the copy is still checked out), if we
1770 either own the copy or are the circulation location, and if the
1771 circulation is for the optional $user argument. $circ and $copy are
1772 required. $user is optional.
1773
1774 Returns a problem if any of the above conditions fail. Returns undef
1775 if they pass and we can proceed with the checkin or renewal.
1776
1777 If the failure occurred on the copy-related checks, then the
1778 ProblemElement field will be undefined and needs to be filled in with
1779 the item id field name. If the check for the copy being checked out to
1780 the provided user fails, then both ProblemElement and ProblemValue
1781 fields will be empty and need to be filled in by the caller.
1782
1783 =cut
1784
1785 sub check_circ_details {
1786     my ($self, $circ, $copy, $user) = @_;
1787
1788     # Shortcut for the next check.
1789     my $ou_id = $self->{session}->{work_ou}->id();
1790
1791     if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1792         # Item isn't checked out.
1793         return NCIP::Problem->new(
1794             {
1795                 ProblemType => 'Item Not Checked Out',
1796                 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1797                 ProblemValue => $copy->barcode()
1798             }
1799         );
1800     } else {
1801         # Get data on the patron who has it checked out.
1802         my $circ_user = $self->retrieve_user_by_id($circ->usr());
1803         if ($user && $circ_user && $user->id() != $circ_user->id()) {
1804             # The ProblemElement and ProblemValue field need to be
1805             # filled in by the caller.
1806             return NCIP::Problem->new(
1807                 {
1808                     ProblemType => 'Item Not Checked Out To This User',
1809                     ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1810                 }
1811             );
1812         }
1813     }
1814     # If we get here, we're good to go.
1815     return undef;
1816 }
1817
1818 =head2 retrieve_copy_details_by_barcode
1819
1820     $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1821
1822 Look up and retrieve some copy details by the copy barcode. This
1823 method returns either a hashref with the copy details or undefined if
1824 no copy exists with that barcode or if some error occurs.
1825
1826 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1827
1828 This method differs from C<retrieve_user_by_barcode> in that a copy
1829 cannot be invalid if it exists and it is not always an error if no
1830 copy exists. In some cases, when handling AcceptItem, we might prefer
1831 there to be no copy.
1832
1833 =cut
1834
1835 sub retrieve_copy_details_by_barcode {
1836     my $self = shift;
1837     my $barcode = shift;
1838
1839     my $copy = $U->simplereq(
1840         'open-ils.circ',
1841         'open-ils.circ.copy_details.retrieve.barcode',
1842         $self->{session}->{authtoken},
1843         $barcode
1844     );
1845
1846     # If $copy is an event, return undefined.
1847     if ($copy && $U->event_code($copy)) {
1848         undef($copy);
1849     }
1850
1851     return $copy;
1852 }
1853
1854 =head2 retrieve_copy_status
1855
1856     $status = $ils->retrieve_copy_status($id);
1857
1858 Retrive a copy status object by database ID.
1859
1860 =cut
1861
1862 sub retrieve_copy_status {
1863     my $self = shift;
1864     my $id = shift;
1865
1866     my $status = $U->simplereq(
1867         'open-ils.pcrud',
1868         'open-ils.pcrud.retrieve.ccs',
1869         $self->{session}->{authtoken},
1870         $id
1871     );
1872
1873     return $status;
1874 }
1875
1876 =head2 retrieve_org_unit_by_shortname
1877
1878     $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1879
1880 Retrieves an org. unit from the database by shortname. Returns the
1881 org. unit as a Fieldmapper object or undefined.
1882
1883 =cut
1884
1885 sub retrieve_org_unit_by_shortname {
1886     my $self = shift;
1887     my $shortname = shift;
1888
1889     my $aou = $U->simplereq(
1890         'open-ils.actor',
1891         'open-ils.actor.org_unit.retrieve_by_shortname',
1892         $shortname
1893     );
1894
1895     return $aou;
1896 }
1897
1898 =head2 retrieve_copy_location
1899
1900     $location = $ils->retrieve_copy_location($location_id);
1901
1902 Retrieve a copy location based on id.
1903
1904 =cut
1905
1906 sub retrieve_copy_location {
1907     my $self = shift;
1908     my $id = shift;
1909
1910     my $location = $U->simplereq(
1911         'open-ils.pcrud',
1912         'open-ils.pcrud.retrieve.acpl',
1913         $self->{session}->{authtoken},
1914         $id
1915     );
1916
1917     return $location;
1918 }
1919
1920 =head2 retrieve_biblio_record_entry
1921
1922     $bre = $ils->retrieve_biblio_record_entry($bre_id);
1923
1924 Given a biblio.record_entry.id, this method retrieves a bre object.
1925
1926 =cut
1927
1928 sub retrieve_biblio_record_entry {
1929     my $self = shift;
1930     my $id = shift;
1931
1932     my $bre = $U->simplereq(
1933         'open-ils.pcrud',
1934         'open-ils.pcrud.retrieve.bre',
1935         $self->{session}->{authtoken},
1936         $id
1937     );
1938
1939     return $bre;
1940 }
1941
1942 =head2 create_precat_copy
1943
1944     $item_info->{
1945         barcode => '312340123456789',
1946         author => 'Public, John Q.',
1947         title => 'Magnum Opus',
1948         call_number => '005.82',
1949         publisher => 'Brick House',
1950         publication_date => '2014'
1951     };
1952
1953     $item = $ils->create_precat_copy($item_info);
1954
1955
1956 Create a "precat" copy to use for the incoming item using a hashref of
1957 item information. At a minimum, the barcode, author and title fields
1958 need to be filled in. The other fields are ignored if provided.
1959
1960 This method is called by the AcceptItem handler if the C<use_precats>
1961 configuration option is turned on.
1962
1963 =cut
1964
1965 sub create_precat_copy {
1966     my $self = shift;
1967     my $item_info = shift;
1968
1969     my $item = Fieldmapper::asset::copy->new();
1970     $item->barcode($item_info->{barcode});
1971     $item->call_number(OILS_PRECAT_CALL_NUMBER);
1972     $item->dummy_title($item_info->{title});
1973     $item->dummy_author($item_info->{author});
1974     $item->circ_lib($self->{session}->{work_ou}->id());
1975     $item->circulate('t');
1976     $item->holdable('t');
1977     $item->opac_visible('f');
1978     $item->deleted('f');
1979     $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1980     $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1981     $item->location(1);
1982     $item->status(0);
1983     $item->editor($self->{session}->{user}->id());
1984     $item->creator($self->{session}->{user}->id());
1985     $item->isnew(1);
1986
1987     # Actually create it:
1988     my $xact;
1989     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1990     $ses->connect();
1991     eval {
1992         $xact = $ses->request(
1993             'open-ils.pcrud.transaction.begin',
1994             $self->{session}->{authtoken}
1995         )->gather(1);
1996         $item = $ses->request(
1997             'open-ils.pcrud.create.acp',
1998             $self->{session}->{authtoken},
1999             $item
2000         )->gather(1);
2001         $xact = $ses->request(
2002             'open-ils.pcrud.transaction.commit',
2003             $self->{session}->{authtoken}
2004         )->gather(1);
2005     };
2006     if ($@) {
2007         undef($item);
2008         if ($xact) {
2009             eval {
2010                 $ses->request(
2011                     'open-ils.pcrud.transaction.rollback',
2012                     $self->{session}->{authtoken}
2013                 )->gather(1);
2014             };
2015         }
2016     }
2017     $ses->disconnect();
2018
2019     return $item;
2020 }
2021
2022 =head2 create_fuller_copy
2023
2024     $item_info->{
2025         barcode => '31234003456789',
2026         author => 'Public, John Q.',
2027         title => 'Magnum Opus',
2028         call_number => '005.82',
2029         publisher => 'Brick House',
2030         publication_date => '2014'
2031     };
2032
2033     $item = $ils->create_fuller_copy($item_info);
2034
2035 Creates a skeletal bibliographic record, call number, and copy for the
2036 incoming item using a hashref with item information in it. At a
2037 minimum, the barcode, author, title, and call_number fields must be
2038 filled in.
2039
2040 This method is used by the AcceptItem handler if the C<use_precats>
2041 configuration option is NOT set.
2042
2043 =cut
2044
2045 sub create_fuller_copy {
2046     my $self = shift;
2047     my $item_info = shift;
2048
2049     my $item;
2050
2051     # We do everything in one transaction, because it should be atomic.
2052     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
2053     $ses->connect();
2054     my $xact;
2055     eval {
2056         $xact = $ses->request(
2057             'open-ils.pcrud.transaction.begin',
2058             $self->{session}->{authtoken}
2059         )->gather(1);
2060     };
2061     if ($@) {
2062         undef($xact);
2063     }
2064
2065     # The rest depends on there being a transaction.
2066     if ($xact) {
2067
2068         # Create the MARC record.
2069         my $record = MARC::Record->new();
2070         $record->encoding('UTF-8');
2071         $record->leader('00881nam a2200193   4500');
2072         my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
2073         my @fields = ();
2074         push(@fields, MARC::Field->new('005', $datespec));
2075         push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
2076         push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
2077         # Publisher is a little trickier:
2078         if ($item_info->{publisher}) {
2079             my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
2080             $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
2081             push(@fields, $pub);
2082         }
2083         # We have no idea if the author is personal corporate or something else, so we use a 720.
2084         push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
2085         $record->append_fields(@fields);
2086         my $marc = clean_marc($record);
2087
2088         # Create the bib object.
2089         my $bib = Fieldmapper::biblio::record_entry->new();
2090         $bib->creator($self->{session}->{user}->id());
2091         $bib->editor($self->{session}->{user}->id());
2092         $bib->source($self->{bib_source}->id());
2093         $bib->active('t');
2094         $bib->deleted('f');
2095         $bib->marc($marc);
2096         $bib->isnew(1);
2097
2098         eval {
2099             $bib = $ses->request(
2100                 'open-ils.pcrud.create.bre',
2101                 $self->{session}->{authtoken},
2102                 $bib
2103             )->gather(1);
2104         };
2105         if ($@) {
2106             undef($bib);
2107             eval {
2108                 $ses->request(
2109                     'open-ils.pcrud.transaction.rollback',
2110                     $self->{session}->{authtoken}
2111                 )->gather(1);
2112             };
2113         }
2114
2115         # Create the call number
2116         my $acn;
2117         if ($bib) {
2118             $acn = Fieldmapper::asset::call_number->new();
2119             $acn->creator($self->{session}->{user}->id());
2120             $acn->editor($self->{session}->{user}->id());
2121             $acn->label($item_info->{call_number});
2122             $acn->record($bib->id());
2123             $acn->owning_lib($self->{session}->{work_ou}->id());
2124             $acn->deleted('f');
2125             $acn->isnew(1);
2126
2127             eval {
2128                 $acn = $ses->request(
2129                     'open-ils.pcrud.create.acn',
2130                     $self->{session}->{authtoken},
2131                     $acn
2132                 )->gather(1);
2133             };
2134             if ($@) {
2135                 undef($acn);
2136                 eval {
2137                     $ses->request(
2138                         'open-ils.pcrud.transaction.rollback',
2139                         $self->{session}->{authtoken}
2140                     )->gather(1);
2141                 };
2142             }
2143         }
2144
2145         # create the copy
2146         if ($acn) {
2147             $item = Fieldmapper::asset::copy->new();
2148             $item->barcode($item_info->{barcode});
2149             $item->call_number($acn->id());
2150             $item->circ_lib($self->{session}->{work_ou}->id);
2151             $item->circulate('t');
2152             if ($self->{config}->{items}->{use_force_holds}) {
2153                 $item->holdable('f');
2154             } else {
2155                 $item->holdable('t');
2156             }
2157             $item->opac_visible('f');
2158             $item->deleted('f');
2159             $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
2160             $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
2161             $item->location(1);
2162             $item->status(0);
2163             $item->editor($self->{session}->{user}->id);
2164             $item->creator($self->{session}->{user}->id);
2165             $item->isnew(1);
2166
2167             eval {
2168                 $item = $ses->request(
2169                     'open-ils.pcrud.create.acp',
2170                     $self->{session}->{authtoken},
2171                     $item
2172                 )->gather(1);
2173
2174                 # Cross our fingers and commit the work.
2175                 $xact = $ses->request(
2176                     'open-ils.pcrud.transaction.commit',
2177                     $self->{session}->{authtoken}
2178                 )->gather(1);
2179             };
2180             if ($@) {
2181                 undef($item);
2182                 eval {
2183                     $ses->request(
2184                         'open-ils.pcrud.transaction.rollback',
2185                         $self->{session}->{authtoken}
2186                     )->gather(1) if ($xact);
2187                 };
2188             }
2189         }
2190     }
2191
2192     # We need to disconnect our session.
2193     $ses->disconnect();
2194
2195     # Now, we handle our asset stat_cat entries.
2196     if ($item) {
2197         # It would be nice to do these in the above transaction, but
2198         # pcrud does not support the ascecm object, yet.
2199         foreach my $entry (@{$self->{stat_cat_entries}}) {
2200             my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2201             $map->isnew(1);
2202             $map->stat_cat($entry->stat_cat());
2203             $map->stat_cat_entry($entry->id());
2204             $map->owning_copy($item->id());
2205             # We don't really worry if it succeeds or not.
2206             $U->simplereq(
2207                 'open-ils.circ',
2208                 'open-ils.circ.stat_cat.asset.copy_map.create',
2209                 $self->{session}->{authtoken},
2210                 $map
2211             );
2212         }
2213     }
2214
2215     return $item;
2216 }
2217
2218 =head2 place_hold
2219
2220     $hold = $ils->place_hold($item, $user, $location, $expiration);
2221
2222 This function places a hold on $item for $user for pickup at
2223 $location. If location is not provided or undefined, the user's home
2224 library is used as a fallback.
2225
2226 The $expiration argument is optional and must be a properly formatted
2227 ISO date time. It will be used as the hold expire time, if
2228 provided. Otherwise the system default time will be used.
2229
2230 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2231 (biblio::record_entry). The appropriate hold type will be placed
2232 depending on the object.
2233
2234 On success, the method returns the object representing the hold. On
2235 failure, a NCIP::Problem object, describing the failure, is returned.
2236
2237 =cut
2238
2239 sub place_hold {
2240     my $self = shift;
2241     my $item = shift;
2242     my $user = shift;
2243     my $location = shift;
2244     my $expiration = shift;
2245
2246     # If $location is undefined, use the user's home_ou, which should
2247     # have been fleshed when the user was retrieved.
2248     $location = $user->home_ou() unless ($location);
2249
2250     # $hold is the hold. $params is for the is_possible check.
2251     my ($hold, $params);
2252
2253     # Prep the hold with fields common to all hold types:
2254     $hold = Fieldmapper::action::hold_request->new();
2255     $hold->isnew(1); # Just to make sure.
2256     $hold->target($item->id());
2257     $hold->usr($user->id());
2258     $hold->pickup_lib($location->id());
2259     $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2260     if (!$user->email()) {
2261         $hold->email_notify('f');
2262         $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2263     } else {
2264         $hold->email_notify('t');
2265     }
2266
2267     # Ditto the params:
2268     $params = { pickup_lib => $location->id(), patronid => $user->id() };
2269
2270     if (ref($item) eq 'Fieldmapper::asset::copy') {
2271         my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2272         $hold->hold_type($type);
2273         $hold->current_copy($item->id());
2274         $params->{hold_type} = $type;
2275         $params->{copy_id} = $item->id();
2276     } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2277         $hold->hold_type('V');
2278         $params->{hold_type} = 'V';
2279         $params->{volume_id} = $item->id();
2280     } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2281         $hold->hold_type('T');
2282         $params->{hold_type} = 'T';
2283         $params->{titleid} = $item->id();
2284     }
2285
2286     # Check for a duplicate hold:
2287     my $duplicate = $U->simplereq(
2288         'open-ils.pcrud',
2289         'open-ils.pcrud.search.ahr',
2290         $self->{session}->{authtoken},
2291         {
2292             hold_type => $hold->hold_type(),
2293             target => $hold->target(),
2294             usr => $hold->usr(),
2295             expire_time => {'>' => 'now'},
2296             cancel_time => undef,
2297             fulfillment_time => undef
2298         }
2299     );
2300     if ($duplicate) {
2301         return NCIP::Problem->new(
2302             {
2303                 ProblemType => 'Duplicate Request',
2304                 ProblemDetail => 'A request for this item already exists for this patron.',
2305                 ProblemElement => 'NULL',
2306                 ProblemValue => 'NULL'
2307             }
2308         );
2309     }
2310
2311     # Check if the hold is possible:
2312     my $r = $U->simplereq(
2313         'open-ils.circ',
2314         'open-ils.circ.title_hold.is_possible',
2315         $self->{session}->{authtoken},
2316         $params
2317     );
2318
2319     if ($r->{success}) {
2320         $hold = $U->simplereq(
2321             'open-ils.circ',
2322             'open-ils.circ.holds.create.override',
2323             $self->{session}->{authtoken},
2324             $hold
2325         );
2326         if (ref($hold) eq 'HASH') {
2327             $hold = _problem_from_event('Request Not Possible', $hold);
2328         }
2329     } elsif ($r->{last_event}) {
2330         $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2331     } elsif ($r->{textcode}) {
2332         $hold = _problem_from_event('Request Not Possible', $r);
2333     } else {
2334         $hold = _problem_from_event('Request Not Possible');
2335     }
2336
2337     return $hold;
2338 }
2339
2340 =head2 cancel_hold
2341
2342     $ils->cancel_hold($hold);
2343
2344 This method cancels the hold argument. It makes no checks on the hold,
2345 so if there are certain conditions that need to be fulfilled before
2346 the hold is canceled, then you must check them before calling this
2347 method.
2348
2349 It returns undef on success or failure. If it fails, you've usually
2350 got bigger problems.
2351
2352 =cut
2353
2354 sub cancel_hold {
2355     my $self = shift;
2356     my $hold = shift;
2357
2358     my $r = $U->simplereq(
2359         'open-ils.circ',
2360         'open-ils.circ.hold.cancel',
2361         $self->{session}->{authtoken},
2362         $hold->id(),
2363         '5',
2364         'Canceled via NCIPServer'
2365     );
2366
2367     return undef;
2368 }
2369
2370 =head2 delete_copy
2371
2372     $ils->delete_copy($copy);
2373
2374 Deletes the copy, and if it is owned by our work_ou and not a precat,
2375 we also delete the volume and bib on which the copy depends.
2376
2377 =cut
2378
2379 sub delete_copy {
2380     my $self = shift;
2381     my $copy = shift;
2382
2383     # Shortcut for ownership checks below.
2384     my $ou_id = $self->{session}->{work_ou}->id();
2385
2386     # First, make sure the copy is not already deleted and we own it.
2387     return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2388
2389     # Indicate we want to delete the copy.
2390     $copy->isdeleted(1);
2391
2392     # Delete the copy using a backend call that will delete the copy,
2393     # the call number, and bib when appropriate.
2394     my $result = $U->simplereq(
2395         'open-ils.cat',
2396         'open-ils.cat.asset.copy.fleshed.batch.update.override',
2397         $self->{session}->{authtoken},
2398         [$copy]
2399     );
2400
2401     # We are currently not checking for succes or failure of the
2402     # above. At some point, someone may want to.
2403
2404     return undef;
2405 }
2406
2407 =head2 copy_can_circulate
2408
2409     $can_circulate = $ils->copy_can_circulate($copy);
2410
2411 Check if the copy's location and the copy itself allow
2412 circulation. Return true if they do, and false if they do not.
2413
2414 =cut
2415
2416 sub copy_can_circulate {
2417     my $self = shift;
2418     my $copy = shift;
2419
2420     my $location = $copy->location();
2421     unless (ref($location)) {
2422         $location = $self->retrieve_copy_location($location);
2423     }
2424
2425     return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2426 }
2427
2428 =head2 copy_can_fulfill
2429
2430     $can_fulfill = $ils->copy_can_fulfill($copy);
2431
2432 Check if the copy's location and the copy itself allow
2433 holds. Return true if they do, and false if they do not.
2434
2435 =cut
2436
2437 sub copy_can_fulfill {
2438     my $self = shift;
2439     my $copy = shift;
2440
2441     my $location = $copy->location();
2442     unless (ref($location)) {
2443         $location = $self->retrieve_copy_location($location);
2444     }
2445
2446     return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2447 }
2448
2449 =head1 OVERRIDDEN PARENT METHODS
2450
2451 =head2 find_user_barcode
2452
2453 We dangerously override our parent's C<find_user_barcode> to return
2454 either the $barcode or a Problem object. In list context the barcode
2455 or problem will be the first argument and the id field, if any, will
2456 be the second. We also add a second, optional, argument to indicate a
2457 default value for the id field in the event of a failure to find
2458 anything at all. (Perl lets us get away with this.)
2459
2460 =cut
2461
2462 sub find_user_barcode {
2463     my $self = shift;
2464     my $request = shift;
2465     my $default = shift;
2466
2467     unless ($default) {
2468         my $message = $self->parse_request_type($request);
2469         if ($message eq 'LookupUser') {
2470             $default = 'AuthenticationInputData';
2471         } else {
2472             $default = 'UserIdentifierValue';
2473         }
2474     }
2475
2476     my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2477
2478     unless ($value) {
2479         $idfield = $default unless ($idfield);
2480         $value = NCIP::Problem->new();
2481         $value->ProblemType('Needed Data Missing');
2482         $value->ProblemDetail('Cannot find user barcode in message.');
2483         $value->ProblemElement($idfield);
2484         $value->ProblemValue('NULL');
2485     }
2486
2487     return (wantarray) ? ($value, $idfield) : $value;
2488 }
2489
2490 =head2 find_item_barcode
2491
2492 We do pretty much the same thing as with C<find_user_barcode> for
2493 C<find_item_barcode>.
2494
2495 =cut
2496
2497 sub find_item_barcode {
2498     my $self = shift;
2499     my $request = shift;
2500     my $default = shift || 'ItemIdentifierValue';
2501
2502     my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2503
2504     unless ($value) {
2505         $idfield = $default unless ($idfield);
2506         $value = NCIP::Problem->new();
2507         $value->ProblemType('Needed Data Missing');
2508         $value->ProblemDetail('Cannot find item barcode in message.');
2509         $value->ProblemElement($idfield);
2510         $value->ProblemValue('NULL');
2511     }
2512
2513     return (wantarray) ? ($value, $idfield) : $value;
2514 }
2515
2516 =head2 find_target_via_bibliographic_id
2517
2518     $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2519
2520 Searches for a bibliographic record to put on hold and returns an
2521 appropriate hold target item depending upon what it finds. If an
2522 appropriate, single target cannot be found, it returns an
2523 NCIP::Problem with the problem message.
2524
2525 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2526 identifiers. If nothing is found, this method can return undef. (Gotta
2527 love Perl and untyped/weakly typed languages in general!)
2528
2529 TODO: Figure out how to search OCLC numbers. We probably need to use
2530 "MARC Expert Search" if we don't want to do a JSON query on
2531 metabib.full_rec.
2532
2533 =cut
2534
2535 sub find_target_via_bibliographic_id {
2536     my $self = shift;
2537     my @biblio_ids = @_;
2538
2539     # The item that we find:
2540     my $item;
2541
2542     # Id for our bib in Evergreen:
2543     my $bibid;
2544
2545     # First, let's look for a SYSNUMBER:
2546     my ($idobj) = grep
2547         { $_->{BibliographicRecordIdentifierCode} eq 'SYSNUMBER' || $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER'
2548               || $_->{AgencyId} }
2549             @biblio_ids;
2550     if ($idobj) {
2551         my $loc;
2552         # BibliographicRecordId can have an AgencyId field if the
2553         # BibliographicRecordIdentifierCode is absent.
2554         if ($idobj->{AgencyId}) {
2555             $bibid = $idobj->{BibliographicRecordIdentifier};
2556             my $locname = $idobj->{AgencyId};
2557             if ($locname) {
2558                 $locname =~ s/.*://;
2559                 $loc = $self->retrieve_org_unit_by_shortname($locname);
2560             }
2561         } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2562             $bibid = $idobj->{BibliographicRecordIdentifierCode}
2563         } else {
2564             $bibid = $idobj->{BibliographicItemIdentifierCode}
2565         }
2566         if ($bibid && $loc) {
2567             $item = $self->_call_number_search($bibid, $loc);
2568         } else {
2569             $item = $U->simplereq(
2570                 'open-ils.pcrud',
2571                 'open-ils.pcrud.retrieve.bre',
2572                 $self->{session}->{authtoken},
2573                 $bibid
2574             );
2575         }
2576         # Check if item is deleted so we'll look for more
2577         # possibilties.
2578         undef($item) if ($item && $U->is_true($item->deleted()));
2579     }
2580
2581     # Build an array of id objects based on the other identifier fields.
2582     my @idobjs = grep
2583         {
2584             $_->{BibliographicRecordIdentifierCode} eq 'ISBN' || $_->{BibliographicItemIdentifierCode} eq 'ISBN'
2585             ||
2586             $_->{BibliographicRecordIdentifierCode} eq 'ISSN' || $_->{BibliographicItemIdentifierCode} eq 'ISSN'
2587         } @biblio_ids;
2588
2589     if (@idobjs) {
2590         my $stashed_problem;
2591         # Reuse $idobj from above.
2592         foreach $idobj (@idobjs) {
2593             my ($idvalue, $idtype, $idfield);
2594             if ($_->{BibliographicItemIdentifier}) {
2595                 $idvalue = $_->{BibliographicItemIdentifier};
2596                 $idtype = $_->{BibliographicItemIdentifierCode};
2597                 $idfield = 'BibliographicItemIdentifier';
2598             } else {
2599                 $idvalue = $_->{BibliographicRecordIdentifier};
2600                 $idtype = $_->{BibliographicRecordIdentifierCode};
2601                 $idfield = 'BibliographicRecordIdentifier';
2602             }
2603             $item = $self->_bib_search($idvalue, $idtype);
2604             if (ref($item) eq 'NCIP::Problem') {
2605                 $stashed_problem = $item unless($stashed_problem);
2606                 $stashed_problem->ProblemElement($idfield);
2607                 undef($item);
2608             }
2609             last if ($item);
2610         }
2611         $item = $stashed_problem if (!$item && $stashed_problem);
2612     }
2613
2614     return $item;
2615 }
2616
2617 # private subroutines not meant to be used directly by subclasses.
2618 # Most have to do with setup and/or state checking of implementation
2619 # components.
2620
2621 # Find, load, and parse our configuration file:
2622 sub _configure {
2623     my $self = shift;
2624
2625     # Find the configuration file via variables:
2626     my $file = OILS_NCIP_CONFIG_DEFAULT;
2627     $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2628
2629     $self->{config} = XMLin($file, NormaliseSpace => 2,
2630                             ForceArray => ['block_profile', 'stat_cat_entry']);
2631 }
2632
2633 # Bootstrap OpenSRF::System and load the IDL.
2634 sub _bootstrap {
2635     my $self = shift;
2636
2637     my $bootstrap_config = $self->{config}->{bootstrap};
2638     OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2639
2640     my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2641     Fieldmapper->import(IDL => $idl);
2642 }
2643
2644 # Login and then initialize some object data based on the
2645 # configuration.
2646 sub _init {
2647     my $self = shift;
2648
2649     # Login to Evergreen.
2650     $self->login();
2651
2652     # Load the barred groups as pgt objects into a blocked_profiles
2653     # list.
2654     $self->{blocked_profiles} = [];
2655     foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2656         my $pgt;
2657         if (ref $_) {
2658             $pgt = $U->simplereq(
2659                 'open-ils.pcrud',
2660                 'open-ils.pcrud.retrieve.pgt',
2661                 $self->{session}->{authtoken},
2662                 $_->{grp}
2663             );
2664         } else {
2665             $pgt = $U->simplereq(
2666                 'open-ils.pcrud',
2667                 'open-ils.pcrud.search.pgt',
2668                 $self->{session}->{authtoken},
2669                 {name => $_}
2670             );
2671         }
2672         push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2673     }
2674
2675     # Load the bib source if we're not using precats.
2676     unless ($self->{config}->{items}->{use_precats}) {
2677         # Retrieve the default
2678         $self->{bib_source} = $U->simplereq(
2679             'open-ils.pcrud',
2680             'open-ils.pcrud.retrieve.cbs',
2681             $self->{session}->{authtoken},
2682             BIB_SOURCE_DEFAULT);
2683         my $data = $self->{config}->{items}->{bib_source};
2684         if ($data) {
2685             $data = $data->[0] if (ref($data) eq 'ARRAY');
2686             my $result;
2687             if (ref $data) {
2688                 $result = $U->simplereq(
2689                     'open-ils.pcrud',
2690                     'open-ils.pcrud.retrieve.cbs',
2691                     $self->{session}->{authtoken},
2692                     $data->{cbs}
2693                 );
2694             } else {
2695                 $result = $U->simplereq(
2696                     'open-ils.pcrud',
2697                     'open-ils.pcrud.search.cbs',
2698                     $self->{session}->{authtoken},
2699                     {source => $data}
2700                 );
2701             }
2702             $self->{bib_source} = $result if ($result);
2703         }
2704     }
2705
2706     # Load the required asset.stat_cat_entries:
2707     $self->{stat_cat_entries} = [];
2708     # First, make a regex for our ou and ancestors:
2709     my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2710     my $re = qr/(?:$ancestors)/;
2711     # Get the uniq stat_cat ids from the configuration:
2712     my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2713     # Retrieve all of the fleshed stat_cats and entries for the above.
2714     my $stat_cats = $U->simplereq(
2715         'open-ils.circ',
2716         'open-ils.circ.stat_cat.asset.retrieve.batch',
2717         $self->{session}->{authtoken},
2718         @cats
2719     );
2720     foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2721         # Must have the stat_cat attr and the name, so we must have a
2722         # reference.
2723         next unless(ref $entry);
2724         my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2725         push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2726     }
2727 }
2728
2729 # Search asset.call_number by a bre.id and location object. Return the
2730 # "closest" call_number if found, undef otherwise.
2731 sub _call_number_search {
2732     my $self = shift;
2733     my $bibid = shift;
2734     my $location = shift;
2735
2736     # At some point, this should be smarter, and we should retrieve
2737     # ancestors and descendants and search with a JSON query or some
2738     # such with results ordered by proximity to the original location,
2739     # but I don't have time to implement that right now.
2740     my $acn = $U->simplereq(
2741         'open-ils.prcud',
2742         'open-ils.pcrud.search.acn',
2743         $self->{session}->{authtoken},
2744         {record => $bibid, owning_lib => $location->id()}
2745     );
2746
2747     return $acn;
2748 }
2749
2750 # Do a multiclass.query to search for items by isbn or issn.
2751 sub _bib_search {
2752     my $self = shift;
2753     my $idvalue = shift;
2754     my $idtype = shift;
2755     my $item;
2756
2757     my $result = $U->simplereq(
2758         'open-ils.search',
2759         'open-ils.search.biblio.multiclass',
2760         {searches => {lc($idtype) => $idvalue}}
2761     );
2762
2763     if ($result && $result->{count}) {
2764         if ($result->{count} > 1) {
2765             $item = NCIP::Problem->new(
2766                 {
2767                     ProblemType => 'Non-Unique Item',
2768                     ProblemDetail => 'More than one item matches the request.',
2769                     ProblemElement => '',
2770                     ProblemValue => $idvalue
2771                 }
2772             );
2773         }
2774         my $bibid = $result->{ids}->[0]->[0];
2775         $item = $U->simplereq(
2776             'open-ils.pcrud',
2777             'open-ils.pcrud.retrieve.bre',
2778             $self->{session}->{authtoken},
2779             $bibid
2780         );
2781     }
2782
2783     return $item;
2784 }
2785
2786 # Search for holds using the user and copy_details information:
2787 sub _hold_search {
2788     my $self = shift;
2789     my $user = shift;
2790     my $copy_details = shift;
2791
2792     my $hold;
2793
2794     # Retrieve all of the user's active holds, and then search them in Perl.
2795     my $holds_list = $U->simplereq(
2796         'open-ils.circ',
2797         'open-ils.circ.holds.retrieve',
2798         $self->{session}->{authtoken},
2799         $user->id(),
2800         0
2801     );
2802
2803     if ($holds_list && @$holds_list) {
2804         my @holds;
2805         # Look for title holds (the most common), first:
2806         my $targetid = $copy_details->{mvr}->doc_id();
2807         @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2808         unless (@holds) {
2809             # Look for volume holds, the next most common:
2810             $targetid = $copy_details->{volume}->id();
2811             @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2812         }
2813         unless (@holds) {
2814             # Look for copy and force holds, the least likely.
2815             $targetid = $copy_details->{copy}->id();
2816             @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
2817         }
2818         # There should only be 1, at this point, if there are any.
2819         if (@holds) {
2820             $hold = $holds[0];
2821         }
2822     }
2823
2824     return $hold;
2825 }
2826
2827 # Standalone, "helper" functions.  These do not take an object or
2828 # class reference.
2829
2830 # Check if a user is past their expiration date.
2831 sub _expired {
2832     my $user = shift;
2833     my $expired = 0;
2834
2835     # Users might not expire.  If so, they have no expire_date.
2836     if ($user->expire_date()) {
2837         my $expires = DateTime::Format::ISO8601->parse_datetime(
2838             cleanse_ISO8601($user->expire_date())
2839         )->epoch();
2840         my $now = DateTime->now()->epoch();
2841         $expired = $now > $expires;
2842     }
2843
2844     return $expired;
2845 }
2846
2847 # Creates a NCIP Problem from an event. Takes a string for the problem
2848 # type, the event hashref (or a string to use for the detail), and
2849 # optional arguments for the ProblemElement and ProblemValue fields.
2850 sub _problem_from_event {
2851     my ($type, $evt, $element, $value) = @_;
2852
2853     my $detail;
2854
2855     # Check the event.
2856     if (ref($evt)) {
2857         my ($textcode, $desc);
2858
2859         # Get the textcode, if available. Otherwise, use the ilsevent
2860         # "id," if available.
2861         if ($evt->{textcode}) {
2862             $textcode = $evt->{textcode};
2863         } elsif ($evt->{ilsevent}) {
2864             $textcode = $evt->{ilsevent};
2865         }
2866
2867         # Get the description. We favor translated descriptions over
2868         # the English in ils_events.xml.
2869         if ($evt->{desc}) {
2870             $desc = $evt->{desc};
2871         }
2872
2873         # Check if $type was set. As an "undocumented" feature, you
2874         # can pass undef, and we'll use the textcode from the event.
2875         unless ($type) {
2876             if ($textcode) {
2877                 $type = $textcode;
2878             }
2879         }
2880
2881         # Set the detail from some combination of the above.
2882         if ($desc) {
2883             $detail = $desc;
2884         } elsif ($textcode eq 'PERM_FAILURE') {
2885             if ($evt->{ilsperm}) {
2886                 $detail = "Permission denied: " . $evt->{ilsperm};
2887                 $detail =~ s/\.override$//;
2888             }
2889         } elsif ($textcode) {
2890             $detail = "ILS returned $textcode error.";
2891         } else {
2892             $detail = 'Detail not available.';
2893         }
2894
2895     } else {
2896         $detail = $evt;
2897     }
2898
2899     return NCIP::Problem->new(
2900         {
2901             ProblemType => ($type) ? $type : 'Temporary Processing Failure',
2902             ProblemDetail => ($detail) ? $detail : 'Detail not available.',
2903             ProblemElement => ($element) ? $element : 'NULL',
2904             ProblemValue => ($value) ? $value : 'NULL'
2905         }
2906     );
2907 }
2908
2909 1;