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