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