]> git.evergreen-ils.org Git - working/NCIPServer.git/blob - lib/NCIP/ILS/Evergreen.pm
1fda3cc3b99acd9f2ecd8f38f12953a0abf0bcc7
[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 $penalty (@{$user->standing_penalties()}) {
1595             if ($penalty->standing_penalty->block_list()) {
1596                 my @pblocks = split(/\|/, $penalty->standing_penalty->block_list());
1597                 foreach my $block (@blocks) {
1598                     if (grep {$_ =~ /$block/} @pblocks) {
1599                         $problem = NCIP::Problem->new(
1600                             {
1601                                 ProblemType => 'User Blocked',
1602                                 ProblemDetail => 'User blocked from ' .
1603                                     ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1604                                                                         (($block eq 'CIRC') ? 'checkout' : lc($block))),
1605                                 ProblemElement => 'NULL',
1606                                 ProblemValue => 'NULL'
1607                             }
1608                         );
1609                         last;
1610                     }
1611                 }
1612                 last if ($problem);
1613             }
1614         }
1615     }
1616
1617     return $problem;
1618 }
1619
1620 =head2 check_circ_details
1621
1622     $problem = $ils->check_circ_details($circ, $copy, $user);
1623
1624 Checks if we can checkin or renew a circulation. That is, the
1625 circulation is still open (i.e. the copy is still checked out), if we
1626 either own the copy or are the circulation location, and if the
1627 circulation is for the optional $user argument. $circ and $copy are
1628 required. $user is optional.
1629
1630 Returns a problem if any of the above conditions fail. Returns undef
1631 if they pass and we can proceed with the checkin or renewal.
1632
1633 If the failure occurred on the copy-related checks, then the
1634 ProblemElement field will be undefined and needs to be filled in with
1635 the item id field name. If the check for the copy being checked out to
1636 the provided user fails, then both ProblemElement and ProblemValue
1637 fields will be empty and need to be filled in by the caller.
1638
1639 =cut
1640
1641 sub check_circ_details {
1642     my ($self, $circ, $copy, $user) = @_;
1643
1644     # Shortcut for the next check.
1645     my $ou_id = $self->{session}->{work_ou}->id();
1646
1647     if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1648         # Item isn't checked out.
1649         return NCIP::Problem->new(
1650             {
1651                 ProblemType => 'Item Not Checked Out',
1652                 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1653                 ProblemValue => $copy->barcode()
1654             }
1655         );
1656     } else {
1657         # Get data on the patron who has it checked out.
1658         my $circ_user = $self->retrieve_user_by_id($circ->usr());
1659         if ($user && $circ_user && $user->id() != $circ_user->id()) {
1660             # The ProblemElement and ProblemValue field need to be
1661             # filled in by the caller.
1662             return NCIP::Problem->new(
1663                 {
1664                     ProblemType => 'Item Not Checked Out To This User',
1665                     ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1666                 }
1667             );
1668         }
1669     }
1670     # If we get here, we're good to go.
1671     return undef;
1672 }
1673
1674 =head2 retrieve_copy_details_by_barcode
1675
1676     $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1677
1678 Look up and retrieve some copy details by the copy barcode. This
1679 method returns either a hashref with the copy details or undefined if
1680 no copy exists with that barcode or if some error occurs.
1681
1682 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1683
1684 This method differs from C<retrieve_user_by_barcode> in that a copy
1685 cannot be invalid if it exists and it is not always an error if no
1686 copy exists. In some cases, when handling AcceptItem, we might prefer
1687 there to be no copy.
1688
1689 =cut
1690
1691 sub retrieve_copy_details_by_barcode {
1692     my $self = shift;
1693     my $barcode = shift;
1694
1695     my $copy = $U->simplereq(
1696         'open-ils.circ',
1697         'open-ils.circ.copy_details.retrieve.barcode',
1698         $self->{session}->{authtoken},
1699         $barcode
1700     );
1701
1702     # If $copy is an event, return undefined.
1703     if ($copy && $U->event_code($copy)) {
1704         undef($copy);
1705     }
1706
1707     return $copy;
1708 }
1709
1710 =head2 retrieve_org_unit_by_shortname
1711
1712     $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1713
1714 Retrieves an org. unit from the database by shortname. Returns the
1715 org. unit as a Fieldmapper object or undefined.
1716
1717 =cut
1718
1719 sub retrieve_org_unit_by_shortname {
1720     my $self = shift;
1721     my $shortname = shift;
1722
1723     my $aou = $U->simplereq(
1724         'open-ils.actor',
1725         'open-ils.actor.org_unit.retrieve_by_shortname',
1726         $shortname
1727     );
1728
1729     return $aou;
1730 }
1731
1732 =head2 retrieve_copy_location
1733
1734     $location = $ils->retrieve_copy_location($location_id);
1735
1736 Retrieve a copy location based on id.
1737
1738 =cut
1739
1740 sub retrieve_copy_location {
1741     my $self = shift;
1742     my $id = shift;
1743
1744     my $location = $U->simplereq(
1745         'open-ils.pcrud',
1746         'open-ils.pcrud.retrieve.acpl',
1747         $self->{session}->{authtoken},
1748         $id
1749     );
1750
1751     return $location;
1752 }
1753
1754 =head2 retrieve_biblio_record_entry
1755
1756     $bre = $ils->retrieve_biblio_record_entry($bre_id);
1757
1758 Given a biblio.record_entry.id, this method retrieves a bre object.
1759
1760 =cut
1761
1762 sub retrieve_biblio_record_entry {
1763     my $self = shift;
1764     my $id = shift;
1765
1766     my $bre = $U->simplereq(
1767         'open-ils.pcrud',
1768         'open-ils.pcrud.retrieve.bre',
1769         $self->{session}->{authtoken},
1770         $id
1771     );
1772
1773     return $bre;
1774 }
1775
1776 =head2 create_precat_copy
1777
1778     $item_info->{
1779         barcode => '312340123456789',
1780         author => 'Public, John Q.',
1781         title => 'Magnum Opus',
1782         call_number => '005.82',
1783         publisher => 'Brick House',
1784         publication_date => '2014'
1785     };
1786
1787     $item = $ils->create_precat_copy($item_info);
1788
1789
1790 Create a "precat" copy to use for the incoming item using a hashref of
1791 item information. At a minimum, the barcode, author and title fields
1792 need to be filled in. The other fields are ignored if provided.
1793
1794 This method is called by the AcceptItem handler if the C<use_precats>
1795 configuration option is turned on.
1796
1797 =cut
1798
1799 sub create_precat_copy {
1800     my $self = shift;
1801     my $item_info = shift;
1802
1803     my $item = Fieldmapper::asset::copy->new();
1804     $item->barcode($item_info->{barcode});
1805     $item->call_number(OILS_PRECAT_CALL_NUMBER);
1806     $item->dummy_title($item_info->{title});
1807     $item->dummy_author($item_info->{author});
1808     $item->circ_lib($self->{session}->{work_ou}->id());
1809     $item->circulate('t');
1810     $item->holdable('t');
1811     $item->opac_visible('f');
1812     $item->deleted('f');
1813     $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1814     $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1815     $item->location(1);
1816     $item->status(0);
1817     $item->editor($self->{session}->{user}->id());
1818     $item->creator($self->{session}->{user}->id());
1819     $item->isnew(1);
1820
1821     # Actually create it:
1822     my $xact;
1823     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1824     $ses->connect();
1825     eval {
1826         $xact = $ses->request(
1827             'open-ils.pcrud.transaction.begin',
1828             $self->{session}->{authtoken}
1829         )->gather(1);
1830         $item = $ses->request(
1831             'open-ils.pcrud.create.acp',
1832             $self->{session}->{authtoken},
1833             $item
1834         )->gather(1);
1835         $xact = $ses->request(
1836             'open-ils.pcrud.transaction.commit',
1837             $self->{session}->{authtoken}
1838         )->gather(1);
1839     };
1840     if ($@) {
1841         undef($item);
1842         if ($xact) {
1843             eval {
1844                 $ses->request(
1845                     'open-ils.pcrud.transaction.rollback',
1846                     $self->{session}->{authtoken}
1847                 )->gather(1);
1848             };
1849         }
1850     }
1851     $ses->disconnect();
1852
1853     return $item;
1854 }
1855
1856 =head2 create_fuller_copy
1857
1858     $item_info->{
1859         barcode => '31234003456789',
1860         author => 'Public, John Q.',
1861         title => 'Magnum Opus',
1862         call_number => '005.82',
1863         publisher => 'Brick House',
1864         publication_date => '2014'
1865     };
1866
1867     $item = $ils->create_fuller_copy($item_info);
1868
1869 Creates a skeletal bibliographic record, call number, and copy for the
1870 incoming item using a hashref with item information in it. At a
1871 minimum, the barcode, author, title, and call_number fields must be
1872 filled in.
1873
1874 This method is used by the AcceptItem handler if the C<use_precats>
1875 configuration option is NOT set.
1876
1877 =cut
1878
1879 sub create_fuller_copy {
1880     my $self = shift;
1881     my $item_info = shift;
1882
1883     my $item;
1884
1885     # We do everything in one transaction, because it should be atomic.
1886     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1887     $ses->connect();
1888     my $xact;
1889     eval {
1890         $xact = $ses->request(
1891             'open-ils.pcrud.transaction.begin',
1892             $self->{session}->{authtoken}
1893         )->gather(1);
1894     };
1895     if ($@) {
1896         undef($xact);
1897     }
1898
1899     # The rest depends on there being a transaction.
1900     if ($xact) {
1901
1902         # Create the MARC record.
1903         my $record = MARC::Record->new();
1904         $record->encoding('UTF-8');
1905         $record->leader('00881nam a2200193   4500');
1906         my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
1907         my @fields = ();
1908         push(@fields, MARC::Field->new('005', $datespec));
1909         push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
1910         push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
1911         # Publisher is a little trickier:
1912         if ($item_info->{publisher}) {
1913             my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
1914             $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
1915             push(@fields, $pub);
1916         }
1917         # We have no idea if the author is personal corporate or something else, so we use a 720.
1918         push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
1919         $record->append_fields(@fields);
1920         my $marc = clean_marc($record);
1921
1922         # Create the bib object.
1923         my $bib = Fieldmapper::biblio::record_entry->new();
1924         $bib->creator($self->{session}->{user}->id());
1925         $bib->editor($self->{session}->{user}->id());
1926         $bib->source($self->{bib_source}->id());
1927         $bib->active('t');
1928         $bib->deleted('f');
1929         $bib->marc($marc);
1930         $bib->isnew(1);
1931
1932         eval {
1933             $bib = $ses->request(
1934                 'open-ils.pcrud.create.bre',
1935                 $self->{session}->{authtoken},
1936                 $bib
1937             )->gather(1);
1938         };
1939         if ($@) {
1940             undef($bib);
1941             eval {
1942                 $ses->request(
1943                     'open-ils.pcrud.transaction.rollback',
1944                     $self->{session}->{authtoken}
1945                 )->gather(1);
1946             };
1947         }
1948
1949         # Create the call number
1950         my $acn;
1951         if ($bib) {
1952             $acn = Fieldmapper::asset::call_number->new();
1953             $acn->creator($self->{session}->{user}->id());
1954             $acn->editor($self->{session}->{user}->id());
1955             $acn->label($item_info->{call_number});
1956             $acn->record($bib->id());
1957             $acn->owning_lib($self->{session}->{work_ou}->id());
1958             $acn->deleted('f');
1959             $acn->isnew(1);
1960
1961             eval {
1962                 $acn = $ses->request(
1963                     'open-ils.pcrud.create.acn',
1964                     $self->{session}->{authtoken},
1965                     $acn
1966                 )->gather(1);
1967             };
1968             if ($@) {
1969                 undef($acn);
1970                 eval {
1971                     $ses->request(
1972                         'open-ils.pcrud.transaction.rollback',
1973                         $self->{session}->{authtoken}
1974                     )->gather(1);
1975                 };
1976             }
1977         }
1978
1979         # create the copy
1980         if ($acn) {
1981             $item = Fieldmapper::asset::copy->new();
1982             $item->barcode($item_info->{barcode});
1983             $item->call_number($acn->id());
1984             $item->circ_lib($self->{session}->{work_ou}->id);
1985             $item->circulate('t');
1986             if ($self->{config}->{items}->{use_force_holds}) {
1987                 $item->holdable('f');
1988             } else {
1989                 $item->holdable('t');
1990             }
1991             $item->opac_visible('f');
1992             $item->deleted('f');
1993             $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1994             $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1995             $item->location(1);
1996             $item->status(0);
1997             $item->editor($self->{session}->{user}->id);
1998             $item->creator($self->{session}->{user}->id);
1999             $item->isnew(1);
2000
2001             eval {
2002                 $item = $ses->request(
2003                     'open-ils.pcrud.create.acp',
2004                     $self->{session}->{authtoken},
2005                     $item
2006                 )->gather(1);
2007
2008                 # Cross our fingers and commit the work.
2009                 $xact = $ses->request(
2010                     'open-ils.pcrud.transaction.commit',
2011                     $self->{session}->{authtoken}
2012                 )->gather(1);
2013             };
2014             if ($@) {
2015                 undef($item);
2016                 eval {
2017                     $ses->request(
2018                         'open-ils.pcrud.transaction.rollback',
2019                         $self->{session}->{authtoken}
2020                     )->gather(1) if ($xact);
2021                 };
2022             }
2023         }
2024     }
2025
2026     # We need to disconnect our session.
2027     $ses->disconnect();
2028
2029     # Now, we handle our asset stat_cat entries.
2030     if ($item) {
2031         # It would be nice to do these in the above transaction, but
2032         # pcrud does not support the ascecm object, yet.
2033         foreach my $entry (@{$self->{stat_cat_entries}}) {
2034             my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
2035             $map->isnew(1);
2036             $map->stat_cat($entry->stat_cat());
2037             $map->stat_cat_entry($entry->id());
2038             $map->owning_copy($item->id());
2039             # We don't really worry if it succeeds or not.
2040             $U->simplereq(
2041                 'open-ils.circ',
2042                 'open-ils.circ.stat_cat.asset.copy_map.create',
2043                 $self->{session}->{authtoken},
2044                 $map
2045             );
2046         }
2047     }
2048
2049     return $item;
2050 }
2051
2052 =head2 place_hold
2053
2054     $hold = $ils->place_hold($item, $user, $location, $expiration);
2055
2056 This function places a hold on $item for $user for pickup at
2057 $location. If location is not provided or undefined, the user's home
2058 library is used as a fallback.
2059
2060 The $expiration argument is optional and must be a properly formatted
2061 ISO date time. It will be used as the hold expire time, if
2062 provided. Otherwise the system default time will be used.
2063
2064 $item can be a copy (asset::copy), volume (asset::call_number), or bib
2065 (biblio::record_entry). The appropriate hold type will be placed
2066 depending on the object.
2067
2068 On success, the method returns the object representing the hold. On
2069 failure, a NCIP::Problem object, describing the failure, is returned.
2070
2071 =cut
2072
2073 sub place_hold {
2074     my $self = shift;
2075     my $item = shift;
2076     my $user = shift;
2077     my $location = shift;
2078     my $expiration = shift;
2079
2080     # If $location is undefined, use the user's home_ou, which should
2081     # have been fleshed when the user was retrieved.
2082     $location = $user->home_ou() unless ($location);
2083
2084     # $hold is the hold. $params is for the is_possible check.
2085     my ($hold, $params);
2086
2087     # Prep the hold with fields common to all hold types:
2088     $hold = Fieldmapper::action::hold_request->new();
2089     $hold->isnew(1); # Just to make sure.
2090     $hold->target($item->id());
2091     $hold->usr($user->id());
2092     $hold->pickup_lib($location->id());
2093     $hold->expire_time(cleanse_ISO8601($expiration)) if ($expiration);
2094     if (!$user->email()) {
2095         $hold->email_notify('f');
2096         $hold->phone_notify($user->day_phone()) if ($user->day_phone());
2097     } else {
2098         $hold->email_notify('t');
2099     }
2100
2101     # Ditto the params:
2102     $params = { pickup_lib => $location->id(), patronid => $user->id() };
2103
2104     if (ref($item) eq 'Fieldmapper::asset::copy') {
2105         my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
2106         $hold->hold_type($type);
2107         $hold->current_copy($item->id());
2108         $params->{hold_type} = $type;
2109         $params->{copy_id} = $item->id();
2110     } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
2111         $hold->hold_type('V');
2112         $params->{hold_type} = 'V';
2113         $params->{volume_id} = $item->id();
2114     } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
2115         $hold->hold_type('T');
2116         $params->{hold_type} = 'T';
2117         $params->{titleid} = $item->id();
2118     }
2119
2120     # Check for a duplicate hold:
2121     my $duplicate = $U->simplereq(
2122         'open-ils.pcrud',
2123         'open-ils.pcrud.search.ahr',
2124         $self->{session}->{authtoken},
2125         {
2126             hold_type => $hold->hold_type(),
2127             target => $hold->target(),
2128             usr => $hold->usr(),
2129             expire_time => {'>' => 'now'},
2130             cancel_time => undef,
2131             fulfillment_time => undef
2132         }
2133     );
2134     if ($duplicate) {
2135         return NCIP::Problem->new(
2136             {
2137                 ProblemType => 'Duplicate Request',
2138                 ProblemDetail => 'A request for this item already exists for this patron.',
2139                 ProblemElement => 'NULL',
2140                 ProblemValue => 'NULL'
2141             }
2142         );
2143     }
2144
2145     # Check if the hold is possible:
2146     my $r = $U->simplereq(
2147         'open-ils.circ',
2148         'open-ils.circ.title_hold.is_possible',
2149         $self->{session}->{authtoken},
2150         $params
2151     );
2152
2153     if ($r->{success}) {
2154         $hold = $U->simplereq(
2155             'open-ils.circ',
2156             'open-ils.circ.holds.create.override',
2157             $self->{session}->{authtoken},
2158             $hold
2159         );
2160         if (ref($hold) eq 'HASH') {
2161             $hold = _problem_from_event('Request Not Possible', $hold);
2162         }
2163     } elsif ($r->{last_event}) {
2164         $hold = _problem_from_event('Request Not Possible', $r->{last_event});
2165     } elsif ($r->{textcode}) {
2166         $hold = _problem_from_event('Request Not Possible', $r);
2167     } else {
2168         $hold = _problem_from_event('Request Not Possible');
2169     }
2170
2171     return $hold;
2172 }
2173
2174 =head2 cancel_hold
2175
2176     $ils->cancel_hold($hold);
2177
2178 This method cancels the hold argument. It makes no checks on the hold,
2179 so if there are certain conditions that need to be fulfilled before
2180 the hold is canceled, then you must check them before calling this
2181 method.
2182
2183 It returns undef on success or failure. If it fails, you've usually
2184 got bigger problems.
2185
2186 =cut
2187
2188 sub cancel_hold {
2189     my $self = shift;
2190     my $hold = shift;
2191
2192     my $r = $U->simplereq(
2193         'open-ils.circ',
2194         'open-ils.circ.hold.cancel',
2195         $self->{session}->{authtoken},
2196         $hold->id(),
2197         '5',
2198         'Canceled via NCIPServer'
2199     );
2200
2201     return undef;
2202 }
2203
2204 =head2 delete_copy
2205
2206     $ils->delete_copy($copy);
2207
2208 Deletes the copy, and if it is owned by our work_ou and not a precat,
2209 we also delete the volume and bib on which the copy depends.
2210
2211 =cut
2212
2213 sub delete_copy {
2214     my $self = shift;
2215     my $copy = shift;
2216
2217     # Shortcut for ownership checks below.
2218     my $ou_id = $self->{session}->{work_ou}->id();
2219
2220     # First, make sure the copy is not already deleted and we own it.
2221     return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
2222
2223     # Indicate we want to delete the copy.
2224     $copy->isdeleted(1);
2225
2226     # Delete the copy using a backend call that will delete the copy,
2227     # the call number, and bib when appropriate.
2228     my $result = $U->simplereq(
2229         'open-ils.cat',
2230         'open-ils.cat.asset.copy.fleshed.batch.update.override',
2231         $self->{session}->{authtoken},
2232         [$copy]
2233     );
2234
2235     # We are currently not checking for succes or failure of the
2236     # above. At some point, someone may want to.
2237
2238     return undef;
2239 }
2240
2241 =head2 copy_can_circulate
2242
2243     $can_circulate = $ils->copy_can_circulate($copy);
2244
2245 Check if the copy's location and the copy itself allow
2246 circulation. Return true if they do, and false if they do not.
2247
2248 =cut
2249
2250 sub copy_can_circulate {
2251     my $self = shift;
2252     my $copy = shift;
2253
2254     my $location = $copy->location();
2255     unless (ref($location)) {
2256         $location = $self->retrieve_copy_location($location);
2257     }
2258
2259     return ($U->is_true($copy->circulate()) && $U->is_true($location->circulate()));
2260 }
2261
2262 =head2 copy_can_fulfill
2263
2264     $can_fulfill = $ils->copy_can_fulfill($copy);
2265
2266 Check if the copy's location and the copy itself allow
2267 holds. Return true if they do, and false if they do not.
2268
2269 =cut
2270
2271 sub copy_can_fulfill {
2272     my $self = shift;
2273     my $copy = shift;
2274
2275     my $location = $copy->location();
2276     unless (ref($location)) {
2277         $location = $self->retrieve_copy_location($location);
2278     }
2279
2280     return ($U->is_true($copy->holdable()) && $U->is_true($location->holdable()));
2281 }
2282
2283 =head1 OVERRIDDEN PARENT METHODS
2284
2285 =head2 find_user_barcode
2286
2287 We dangerously override our parent's C<find_user_barcode> to return
2288 either the $barcode or a Problem object. In list context the barcode
2289 or problem will be the first argument and the id field, if any, will
2290 be the second. We also add a second, optional, argument to indicate a
2291 default value for the id field in the event of a failure to find
2292 anything at all. (Perl lets us get away with this.)
2293
2294 =cut
2295
2296 sub find_user_barcode {
2297     my $self = shift;
2298     my $request = shift;
2299     my $default = shift;
2300
2301     unless ($default) {
2302         my $message = $self->parse_request_type($request);
2303         if ($message eq 'LookupUser') {
2304             $default = 'AuthenticationInputData';
2305         } else {
2306             $default = 'UserIdentifierValue';
2307         }
2308     }
2309
2310     my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
2311
2312     unless ($value) {
2313         $idfield = $default unless ($idfield);
2314         $value = NCIP::Problem->new();
2315         $value->ProblemType('Needed Data Missing');
2316         $value->ProblemDetail('Cannot find user barcode in message.');
2317         $value->ProblemElement($idfield);
2318         $value->ProblemValue('NULL');
2319     }
2320
2321     return (wantarray) ? ($value, $idfield) : $value;
2322 }
2323
2324 =head2 find_item_barcode
2325
2326 We do pretty much the same thing as with C<find_user_barcode> for
2327 C<find_item_barcode>.
2328
2329 =cut
2330
2331 sub find_item_barcode {
2332     my $self = shift;
2333     my $request = shift;
2334     my $default = shift || 'ItemIdentifierValue';
2335
2336     my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
2337
2338     unless ($value) {
2339         $idfield = $default unless ($idfield);
2340         $value = NCIP::Problem->new();
2341         $value->ProblemType('Needed Data Missing');
2342         $value->ProblemDetail('Cannot find item barcode in message.');
2343         $value->ProblemElement($idfield);
2344         $value->ProblemValue('NULL');
2345     }
2346
2347     return (wantarray) ? ($value, $idfield) : $value;
2348 }
2349
2350 =head2 find_target_via_bibliographic_id
2351
2352     $item = $ils->find_target_via_bibliographic_id(@biblio_ids);
2353
2354 Searches for a bibliographic record to put on hold and returns an
2355 appropriate hold target item depending upon what it finds. If an
2356 appropriate, single target cannot be found, it returns an
2357 NCIP::Problem with the problem message.
2358
2359 Currently, we only look for SYSNUMBER, ISBN, and ISSN record
2360 identifiers. If nothing is found, this method can return undef. (Gotta
2361 love Perl and untyped/weakly typed languages in general!)
2362
2363 TODO: Figure out how to search OCLC numbers. We probably need to use
2364 "MARC Expert Search" if we don't want to do a JSON query on
2365 metabib.full_rec.
2366
2367 =cut
2368
2369 sub find_target_via_bibliographic_id {
2370     my $self = shift;
2371     my @biblio_ids = @_;
2372
2373     # The item that we find:
2374     my $item;
2375
2376     # Id for our bib in Evergreen:
2377     my $bibid;
2378
2379     # First, let's look for a SYSNUMBER:
2380     my ($idobj) = grep
2381         { $_->{BibligraphicRecordIdentifierCode} eq 'SYSNUMBER' || $_->{BibliographicItemIdentifierCode} eq 'SYSNUMBER'
2382               || $_->{AgencyId} }
2383             @biblio_ids;
2384     if ($idobj) {
2385         my $loc;
2386         # BibliographicRecordId can have an AgencyId field if the
2387         # BibliographicRecordIdentifierCode is absent.
2388         if ($idobj->{AgencyId}) {
2389             $bibid = $idobj->{BibliographicRecordIdentifier};
2390             my $locname = $idobj->{AgencyId};
2391             if ($locname) {
2392                 $locname =~ s/.*://;
2393                 $loc = $self->retrieve_org_unit_by_shortname($locname);
2394             }
2395         } elsif ($idobj->{BibliographicRecordIdentifierCode}) {
2396             $bibid = $idobj->{BibliographicRecordIdentifierCode}
2397         } else {
2398             $bibid = $idobj->{BibliographicItemIdentifierCode}
2399         }
2400         if ($bibid && $loc) {
2401             $item = $self->_call_number_search($bibid, $loc);
2402         } else {
2403             $item = $U->simplereq(
2404                 'open-ils.pcrud',
2405                 'open-ils.pcrud.retrieve.bre',
2406                 $self->{session}->{authtoken},
2407                 $bibid
2408             );
2409         }
2410         # Check if item is deleted so we'll look for more
2411         # possibilties.
2412         undef($item) if ($item && $U->is_true($item->deleted()));
2413     }
2414
2415     # Build an array of id objects based on the other identifier fields.
2416     my @idobjs = grep
2417         {
2418             $_->{BibliographicRecordIdentifierCode} eq 'ISBN' || $_->{BibliographicItemIdentifierCode} eq 'ISBN'
2419             ||
2420             $_->{BibliographicRecordIdentifierCode} eq 'ISSN' || $_->{BibliographicItemIdentifierCode} eq 'ISSN'
2421         } @biblio_ids;
2422
2423     if (@idobjs) {
2424         my $stashed_problem;
2425         # Reuse $idobj from above.
2426         foreach $idobj (@idobjs) {
2427             my ($idvalue, $idtype, $idfield);
2428             if ($_->{BibliographicItemIdentifier}) {
2429                 $idvalue = $_->{BibliographicItemIdentifier};
2430                 $idtype = $_->{BibliographicItemIdentifierCode};
2431                 $idfield = 'BibliographicItemIdentifier';
2432             } else {
2433                 $idvalue = $_->{BibliographicRecordIdentifier};
2434                 $idtype = $_->{BibliographicRecordIdentifierCode};
2435                 $idfield = 'BibliographicRecordIdentifier';
2436             }
2437             $item = $self->_bib_search($idvalue, $idtype);
2438             if (ref($item) eq 'NCIP::Problem') {
2439                 $stashed_problem = $item unless($stashed_problem);
2440                 $stashed_problem->ProblemElement($idfield);
2441                 undef($item);
2442             }
2443             last if ($item);
2444         }
2445         $item = $stashed_problem if (!$item && $stashed_problem);
2446     }
2447
2448     return $item;
2449 }
2450
2451 # private subroutines not meant to be used directly by subclasses.
2452 # Most have to do with setup and/or state checking of implementation
2453 # components.
2454
2455 # Find, load, and parse our configuration file:
2456 sub _configure {
2457     my $self = shift;
2458
2459     # Find the configuration file via variables:
2460     my $file = OILS_NCIP_CONFIG_DEFAULT;
2461     $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
2462
2463     $self->{config} = XMLin($file, NormaliseSpace => 2,
2464                             ForceArray => ['block_profile', 'stat_cat_entry']);
2465 }
2466
2467 # Bootstrap OpenSRF::System and load the IDL.
2468 sub _bootstrap {
2469     my $self = shift;
2470
2471     my $bootstrap_config = $self->{config}->{bootstrap};
2472     OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
2473
2474     my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
2475     Fieldmapper->import(IDL => $idl);
2476 }
2477
2478 # Login and then initialize some object data based on the
2479 # configuration.
2480 sub _init {
2481     my $self = shift;
2482
2483     # Login to Evergreen.
2484     $self->login();
2485
2486     # Load the barred groups as pgt objects into a blocked_profiles
2487     # list.
2488     $self->{blocked_profiles} = [];
2489     foreach (@{$self->{config}->{patrons}->{block_profile}}) {
2490         my $pgt;
2491         if (ref $_) {
2492             $pgt = $U->simplereq(
2493                 'open-ils.pcrud',
2494                 'open-ils.pcrud.retrieve.pgt',
2495                 $self->{session}->{authtoken},
2496                 $_->{grp}
2497             );
2498         } else {
2499             $pgt = $U->simplereq(
2500                 'open-ils.pcrud',
2501                 'open-ils.pcrud.search.pgt',
2502                 $self->{session}->{authtoken},
2503                 {name => $_}
2504             );
2505         }
2506         push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
2507     }
2508
2509     # Load the bib source if we're not using precats.
2510     unless ($self->{config}->{items}->{use_precats}) {
2511         # Retrieve the default
2512         $self->{bib_source} = $U->simplereq(
2513             'open-ils.pcrud',
2514             'open-ils.pcrud.retrieve.cbs',
2515             $self->{session}->{authtoken},
2516             BIB_SOURCE_DEFAULT);
2517         my $data = $self->{config}->{items}->{bib_source};
2518         if ($data) {
2519             $data = $data->[0] if (ref($data) eq 'ARRAY');
2520             my $result;
2521             if (ref $data) {
2522                 $result = $U->simplereq(
2523                     'open-ils.pcrud',
2524                     'open-ils.pcrud.retrieve.cbs',
2525                     $self->{session}->{authtoken},
2526                     $data->{cbs}
2527                 );
2528             } else {
2529                 $result = $U->simplereq(
2530                     'open-ils.pcrud',
2531                     'open-ils.pcrud.search.cbs',
2532                     $self->{session}->{authtoken},
2533                     {source => $data}
2534                 );
2535             }
2536             $self->{bib_source} = $result if ($result);
2537         }
2538     }
2539
2540     # Load the required asset.stat_cat_entries:
2541     $self->{stat_cat_entries} = [];
2542     # First, make a regex for our ou and ancestors:
2543     my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
2544     my $re = qr/(?:$ancestors)/;
2545     # Get the uniq stat_cat ids from the configuration:
2546     my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
2547     # Retrieve all of the fleshed stat_cats and entries for the above.
2548     my $stat_cats = $U->simplereq(
2549         'open-ils.circ',
2550         'open-ils.circ.stat_cat.asset.retrieve.batch',
2551         $self->{session}->{authtoken},
2552         @cats
2553     );
2554     foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
2555         # Must have the stat_cat attr and the name, so we must have a
2556         # reference.
2557         next unless(ref $entry);
2558         my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
2559         push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
2560     }
2561 }
2562
2563 # Search asset.call_number by a bre.id and location object. Return the
2564 # "closest" call_number if found, undef otherwise.
2565 sub _call_number_search {
2566     my $self = shift;
2567     my $bibid = shift;
2568     my $location = shift;
2569
2570     # At some point, this should be smarter, and we should retrieve
2571     # ancestors and descendants and search with a JSON query or some
2572     # such with results ordered by proximity to the original location,
2573     # but I don't have time to implement that right now.
2574     my $acn = $U->simplereq(
2575         'open-ils.prcud',
2576         'open-ils.pcrud.search.acn',
2577         $self->{session}->{authtoken},
2578         {record => $bibid, owning_lib => $location->id()}
2579     );
2580
2581     return $acn;
2582 }
2583
2584 # Do a multiclass.query to search for items by isbn or issn.
2585 sub _bib_search {
2586     my $self = shift;
2587     my $idvalue = shift;
2588     my $idtype = shift;
2589     my $item;
2590
2591     my $result = $U->simplereq(
2592         'open-ils.search',
2593         'open-ils.search.biblio.multiclass',
2594         {searches => {lc($idtype) => $idvalue}}
2595     );
2596
2597     if ($result && $result->{count}) {
2598         if ($result->{count} > 1) {
2599             $item = NCIP::Problem->new(
2600                 {
2601                     ProblemType => 'Non-Unique Item',
2602                     ProblemDetail => 'More than one item matches the request.',
2603                     ProblemElement => '',
2604                     ProblemValue => $idvalue
2605                 }
2606             );
2607         }
2608         my $bibid = $result->{ids}->[0]->[0];
2609         $item = $U->simplereq(
2610             'open-ils.pcrud',
2611             'open-ils.pcrud.retrieve.bre',
2612             $self->{session}->{authtoken},
2613             $bibid
2614         );
2615     }
2616
2617     return $item;
2618 }
2619
2620 # Search for holds using the user and copy_details information:
2621 sub _hold_search {
2622     my $self = shift;
2623     my $user = shift;
2624     my $copy_details = shift;
2625
2626     my $hold;
2627
2628     # Retrieve all of the user's active holds, and then search them in Perl.
2629     my $holds_list = $U->simplereq(
2630         'open-ils.circ',
2631         'open-ils.circ.holds.retrieve',
2632         $self->{session}->{authtoken},
2633         $user->id(),
2634         0
2635     );
2636
2637     if ($holds_list && @$holds_list) {
2638         my @holds;
2639         # Look for title holds (the most common), first:
2640         my $targetid = $copy_details->{mvr}->doc_id();
2641         @holds = grep {$_->hold_type eq 'T' && $_->target == $targetid} @{$holds_list};
2642         unless (@holds) {
2643             # Look for volume holds, the next most common:
2644             $targetid = $copy_details->{volume}->id();
2645             @holds = grep {$_->hold_type eq 'V' && $_->target == $targetid} @{$holds_list};
2646         }
2647         unless (@holds) {
2648             # Look for copy and force holds, the least likely.
2649             $targetid = $copy_details->{copy}->id();
2650             @holds = grep {($_->hold_type eq 'C' || $_->hold_type eq 'F') && $_->target == $targetid} @{$holds_list};
2651         }
2652         # There should only be 1, at this point, if there are any.
2653         if (@holds) {
2654             $hold = $holds[0];
2655         }
2656     }
2657
2658     return $hold;
2659 }
2660
2661 # Standalone, "helper" functions.  These do not take an object or
2662 # class reference.
2663
2664 # Check if a user is past their expiration date.
2665 sub _expired {
2666     my $user = shift;
2667     my $expired = 0;
2668
2669     # Users might not expire.  If so, they have no expire_date.
2670     if ($user->expire_date()) {
2671         my $expires = DateTime::Format::ISO8601->parse_datetime(
2672             cleanse_ISO8601($user->expire_date())
2673         )->epoch();
2674         my $now = DateTime->now()->epoch();
2675         $expired = $now > $expires;
2676     }
2677
2678     return $expired;
2679 }
2680
2681 # Creates a NCIP Problem from an event. Takes a string for the problem
2682 # type, the event hashref (or a string to use for the detail), and
2683 # optional arguments for the ProblemElement and ProblemValue fields.
2684 sub _problem_from_event {
2685     my ($type, $evt, $element, $value) = @_;
2686
2687     my $detail;
2688
2689     # Check the event.
2690     if (ref($evt)) {
2691         my ($textcode, $desc);
2692
2693         # Get the textcode, if available. Otherwise, use the ilsevent
2694         # "id," if available.
2695         if ($evt->{textcode}) {
2696             $textcode = $evt->{textcode};
2697         } elsif ($evt->{ilsevent}) {
2698             $textcode = $evt->{ilsevent};
2699         }
2700
2701         # Get the description. We favor translated descriptions over
2702         # the English in ils_events.xml.
2703         if ($evt->{desc}) {
2704             $desc = $evt->{desc};
2705         }
2706
2707         # Check if $type was set. As an "undocumented" feature, you
2708         # can pass undef, and we'll use the textcode from the event.
2709         unless ($type) {
2710             if ($textcode) {
2711                 $type = $textcode;
2712             }
2713         }
2714
2715         # Set the detail from some combination of the above.
2716         if ($desc) {
2717             $detail = $desc;
2718         } elsif ($textcode eq 'PERM_FAILURE') {
2719             if ($evt->{ilsperm}) {
2720                 $detail = "Permission denied: " . $evt->{ilsperm};
2721                 $detail =~ s/\.override$//;
2722             }
2723         } elsif ($textcode) {
2724             $detail = "ILS returned $textcode error.";
2725         } else {
2726             $detail = 'Detail not available.';
2727         }
2728
2729     } else {
2730         $detail = $evt;
2731     }
2732
2733     return NCIP::Problem->new(
2734         {
2735             ProblemType => ($type) ? $type : 'Temporary Processing Failure',
2736             ProblemDetail => ($detail) ? $detail : 'Detail not available.',
2737             ProblemElement => ($element) ? $element : 'NULL',
2738             ProblemValue => ($value) ? $value : 'NULL'
2739         }
2740     );
2741 }
2742
2743 1;