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