]> git.evergreen-ils.org Git - working/NCIPServer.git/blob - lib/NCIP/ILS/Evergreen.pm
Add RenewItem support for NCIP::ILS::Evergreen.
[working/NCIPServer.git] / lib / NCIP / ILS / Evergreen.pm
1 # ---------------------------------------------------------------
2 # Copyright © 2014 Jason J.A. Stephenson <jason@sigio.com>
3 #
4 # This file is part of NCIPServer.
5 #
6 # NCIPServer is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # NCIPServer is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with NCIPServer.  If not, see <http://www.gnu.org/licenses/>.
18 # ---------------------------------------------------------------
19 package NCIP::ILS::Evergreen;
20
21 use Modern::Perl;
22 use XML::LibXML::Simple qw(XMLin);
23 use DateTime;
24 use DateTime::Format::ISO8601;
25 use Digest::MD5 qw/md5_hex/;
26 use OpenSRF::System;
27 use OpenSRF::AppSession;
28 use OpenSRF::Utils qw/:datetime/;
29 use OpenSRF::Utils::SettingsClient;
30 use OpenILS::Utils::Fieldmapper;
31 use OpenILS::Utils::Normalize qw(clean_marc);
32 use OpenILS::Application::AppUtils;
33 use OpenILS::Const qw/:const/;
34 use MARC::Record;
35 use MARC::Field;
36 use MARC::File::XML;
37 use List::MoreUtils qw/uniq/;
38 use POSIX qw/strftime/;
39
40 # We need a bunch of NCIP::* objects.
41 use NCIP::Response;
42 use NCIP::Problem;
43 use NCIP::User;
44 use NCIP::User::OptionalFields;
45 use NCIP::User::AddressInformation;
46 use NCIP::User::Id;
47 use NCIP::User::BlockOrTrap;
48 use NCIP::User::Privilege;
49 use NCIP::User::PrivilegeStatus;
50 use NCIP::StructuredPersonalUserName;
51 use NCIP::StructuredAddress;
52 use NCIP::ElectronicAddress;
53 use NCIP::RequestId;
54 use NCIP::Item::Id;
55
56 # Inherit from NCIP::ILS.
57 use parent qw(NCIP::ILS);
58
59 =head1 NAME
60
61 Evergreen - Evergreen driver for NCIPServer
62
63 =head1 SYNOPSIS
64
65     my $ils = NCIP::ILS::Evergreen->new(name => $config->{NCIP.ils.value});
66
67 =head1 DESCRIPTION
68
69 NCIP::ILS::Evergreen is the default driver for Evergreen and
70 NCIPServer. It was initially developed to work with Auto-Graphics'
71 SHAREit software using a subset of an unspecified ILL/DCB profile.
72
73 =cut
74
75 # Default values we define for things that might be missing in our
76 # runtime environment or configuration file that absolutely must have
77 # values.
78 #
79 # OILS_NCIP_CONFIG_DEFAULT is the default location to find our
80 # driver's configuration file.  This location can be overridden by
81 # setting the path in the OILS_NCIP_CONFIG environment variable.
82 #
83 # BIB_SOURCE_DEFAULT is the config.bib_source.id to use when creating
84 # "short" bibs.  It is used only if no entry is supplied in the
85 # configuration file.  The provided default is 2, the id of the
86 # "System Local" source that comes with a default Evergreen
87 # installation.
88 use constant {
89     OILS_NCIP_CONFIG_DEFAULT => '/openils/conf/oils_ncip.xml',
90     BIB_SOURCE_DEFAULT => 2
91 };
92
93 # A common Evergreen code shortcut to use AppUtils:
94 my $U = 'OpenILS::Application::AppUtils';
95
96 # The usual constructor:
97 sub new {
98     my $class = shift;
99     $class = ref($class) if (ref $class);
100
101     # Instantiate our parent with the rest of the arguments.  It
102     # creates a blessed hashref.
103     my $self = $class->SUPER::new(@_);
104
105     # Look for our configuration file, load, and parse it:
106     $self->_configure();
107
108     # Bootstrap OpenSRF and prepare some OpenILS components.
109     $self->_bootstrap();
110
111     # Initialize the rest of our internal state.
112     $self->_init();
113
114     return $self;
115 }
116
117 =head1 HANDLER METHODS
118
119 =head2 lookupuser
120
121     $ils->lookupuser($request);
122
123 Processes a LookupUser request.
124
125 =cut
126
127 sub lookupuser {
128     my $self = shift;
129     my $request = shift;
130
131     # Check our session and login if necessary.
132     $self->login() unless ($self->checkauth());
133
134     my $message_type = $self->parse_request_type($request);
135
136     # Let's go ahead and create our response object. We need this even
137     # if there is a problem.
138     my $response = NCIP::Response->new({type => $message_type . "Response"});
139     $response->header($self->make_header($request));
140
141     # Need to parse the request object to get the user barcode.
142     my ($barcode, $idfield) = $self->find_user_barcode($request);
143
144     # If we did not find a barcode, then report the problem.
145     if (ref($barcode) eq 'NCIP::Problem') {
146         $response->problem($barcode);
147         return $response;
148     }
149
150     # Look up our patron by barcode:
151     my $user = $self->retrieve_user_by_barcode($barcode, $idfield);
152     if (ref($user) eq 'NCIP::Problem') {
153         $response->problem($user);
154         return $response;
155     }
156
157     # We got the information, so lets fill in our userdata.
158     my $userdata = NCIP::User->new();
159
160     # Make an array of the user's active barcodes.
161     my $ids = [];
162     foreach my $card (@{$user->cards()}) {
163         if ($U->is_true($card->active())) {
164             my $id = NCIP::User::Id->new({
165                 UserIdentifierType => 'Barcode',
166                 UserIdentifierValue => $card->barcode()
167             });
168             push(@$ids, $id);
169         }
170     }
171     $userdata->UserId($ids);
172
173     # Check if they requested any optional fields and return those.
174     my $elements = $request->{$message_type}->{UserElementType};
175     if ($elements) {
176         $elements = [$elements] unless (ref $elements eq 'ARRAY');
177         my $optionalfields = NCIP::User::OptionalFields->new();
178
179         # First, we'll look for name information.
180         if (grep {$_ eq 'Name Information'} @$elements) {
181             my $name = NCIP::StructuredPersonalUserName->new();
182             $name->Surname($user->family_name());
183             $name->GivenName($user->first_given_name());
184             $name->Prefix($user->prefix());
185             $name->Suffix($user->suffix());
186             $optionalfields->NameInformation($name);
187         }
188
189         # Next, check for user address information.
190         if (grep {$_ eq 'User Address Information'} @$elements) {
191             my $addresses = [];
192
193             # See if the user has any valid, physcial addresses.
194             foreach my $addr (@{$user->addresses()}) {
195                 next if ($U->is_true($addr->pending()));
196                 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>$addr->address_type()});
197                 my $physical = NCIP::StructuredAddress->new();
198                 $physical->Line1($addr->street1());
199                 $physical->Line2($addr->street2());
200                 $physical->Locality($addr->city());
201                 $physical->Region($addr->state());
202                 $physical->PostalCode($addr->post_code());
203                 $physical->Country($addr->country());
204                 $address->PhysicalAddress($physical);
205                 push @$addresses, $address;
206             }
207
208             # Right now, we're only sharing email address if the user
209             # has it. We don't share phone numbers.
210             if ($user->email()) {
211                 my $address = NCIP::User::AddressInformation->new({UserAddressRoleType=>'Email Address'});
212                 $address->ElectronicAddress(
213                     NCIP::ElectronicAddress->new({
214                         Type=>'Email Address',
215                         Data=>$user->email()
216                     })
217                 );
218                 push @$addresses, $address;
219             }
220
221             $optionalfields->UserAddressInformation($addresses);
222         }
223
224         # Check for User Privilege.
225         if (grep {$_ eq 'User Privilege'} @$elements) {
226             # Get the user's group:
227             my $pgt = $U->simplereq(
228                 'open-ils.pcrud',
229                 'open-ils.pcrud.retrieve.pgt',
230                 $self->{session}->{authtoken},
231                 $user->profile()
232             );
233             if ($pgt) {
234                 my $privilege = NCIP::User::Privilege->new();
235                 $privilege->AgencyId($user->home_ou->shortname());
236                 $privilege->AgencyUserPrivilegeType($pgt->name());
237                 $privilege->ValidToDate($user->expire_date());
238                 $privilege->ValidFromDate($user->create_date());
239
240                 my $status = 'Active';
241                 if (_expired($user)) {
242                     $status = 'Expired';
243                 } elsif ($U->is_true($user->barred())) {
244                     $status = 'Barred';
245                 } elsif (!$U->is_true($user->active())) {
246                     $status = 'Inactive';
247                 }
248                 if ($status) {
249                     $privilege->UserPrivilegeStatus(
250                         NCIP::User::PrivilegeStatus->new({
251                             UserPrivilegeStatusType => $status
252                         })
253                     );
254                 }
255
256                 $optionalfields->UserPrivilege([$privilege]);
257             }
258         }
259
260         # Check for Block Or Trap.
261         if (grep {$_ eq 'Block Or Trap'} @$elements) {
262             my $blocks = [];
263
264             # First, let's check if the profile is blocked from ILL.
265             if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
266                 my $block = NCIP::User::BlockOrTrap->new();
267                 $block->AgencyId($user->home_ou->shortname());
268                 $block->BlockOrTrapType('Block Interlibrary Loan');
269                 push @$blocks, $block;
270             }
271
272             # Next, we loop through the user's standing penalties
273             # looking for blocks on CIRC, HOLD, and RENEW.
274             my ($have_circ, $have_renew, $have_hold) = (0,0,0);
275             foreach my $penalty (@{$user->standing_penalties()}) {
276                 next unless($penalty->standing_penalty->block_list());
277                 my @block_list = split(/\|/, $penalty->standing_penalty->block_list());
278                 my $ou = $U->simplereq(
279                     'open-ils.pcrud',
280                     'open-ils.pcrud.retrieve.aou',
281                     $self->{session}->{authtoken},
282                     $penalty->org_unit()
283                 );
284
285                 # Block checkout.
286                 if (!$have_circ && grep {$_ eq 'CIRC'} @block_list) {
287                     my $bot = NCIP::User::BlockOrTrap->new();
288                     $bot->AgencyId($ou->shortname());
289                     $bot->BlockOrTrapType('Block Checkout');
290                     push @$blocks, $bot;
291                     $have_circ = 1;
292                 }
293
294                 # Block holds.
295                 if (!$have_hold && grep {$_ eq 'HOLD' || $_ eq 'FULFILL'} @block_list) {
296                     my $bot = NCIP::User::BlockOrTrap->new();
297                     $bot->AgencyId($ou->shortname());
298                     $bot->BlockOrTrapType('Block Holds');
299                     push @$blocks, $bot;
300                     $have_hold = 1;
301                 }
302
303                 # Block renewals.
304                 if (!$have_renew && grep {$_ eq 'RENEW'} @block_list) {
305                     my $bot = NCIP::User::BlockOrTrap->new();
306                     $bot->AgencyId($ou->shortname());
307                     $bot->BlockOrTrapType('Block Renewals');
308                     push @$blocks, $bot;
309                     $have_renew = 1;
310                 }
311
312                 # Stop after we report one of each, even if more
313                 # blocks remain.
314                 last if ($have_circ && $have_renew && $have_hold);
315             }
316
317             $optionalfields->BlockOrTrap($blocks);
318         }
319
320         $userdata->UserOptionalFields($optionalfields);
321     }
322
323     $response->data($userdata);
324
325     return $response;
326 }
327
328 =head2 acceptitem
329
330     $ils->acceptitem($request);
331
332 Processes an AcceptItem request.
333
334 =cut
335
336 sub acceptitem {
337     my $self = shift;
338     my $request = shift;
339
340     # Check our session and login if necessary.
341     $self->login() unless ($self->checkauth());
342
343     # Common preparation.
344     my $message = $self->parse_request_type($request);
345     my $response = NCIP::Response->new({type => $message . 'Response'});
346     $response->header($self->make_header($request));
347
348     # We only accept holds for the time being.
349     if ($request->{$message}->{RequestedActionType} !~ /^hold\w/i) {
350         # We need the item id or we can't do anything at all.
351         my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
352         if (ref($item_barcode) eq 'NCIP::Problem') {
353             $response->problem($item_barcode);
354             return $response;
355         }
356
357         # We need to find a patron barcode or we can't look anyone up
358         # to place a hold.
359         my ($user_barcode, $user_idfield) = $self->find_user_barcode($request, 'UserIdentifierValue');
360         if (ref($user_barcode) eq 'NCIP::Problem') {
361             $response->problem($user_barcode);
362             return $response;
363         }
364         # Look up our patron by barcode:
365         my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
366         if (ref($user) eq 'NCIP::Problem') {
367             $response->problem($user);
368             return $response;
369         }
370         # We're doing patron checks before looking for bibliographic
371         # information and creating the item because problems with the
372         # patron are more likely to occur.
373         my $problem = $self->check_user_for_problems($user, 'HOLD');
374         if ($problem) {
375             $response->problem($problem);
376             return $response;
377         }
378
379         # Check if the item barcode already exists:
380         my $item = $self->retrieve_copy_details_by_barcode($item_barcode);
381         if ($item) {
382             # What to do here was not defined in the
383             # specification. Since the copies that we create this way
384             # should get deleted when checked in, it would be an error
385             # if we try to create another one. It means that something
386             # has gone wrong somewhere.
387             $response->problem(
388                 NCIP::Problem->new(
389                     {
390                         ProblemType => 'Duplicate Item',
391                         ProblemDetail => "Item with barcode $item_barcode already exists.",
392                         ProblemElement => $item_idfield,
393                         ProblemValue => $item_barcode
394                     }
395                 )
396             );
397             return $response;
398         }
399
400         # Now, we have to create our new copy and/or bib and call number.
401
402         # First, we have to gather the necessary information from the
403         # request.  Store in a hashref for convenience. We may write a
404         # method to get this information in the future if we find we
405         # need it in other handlers. Such a function would be a
406         # candidate to go into our parent, NCIP::ILS.
407         my $item_info = {
408             barcode => $item_barcode,
409             call_number => $request->{$message}->{ItemOptionalFields}->{ItemDescription}->{CallNumber},
410             title => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Author},
411             author => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Title},
412             publisher => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{Publisher},
413             publication_date => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{PublicationDate},
414             medium => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{MediumType},
415             electronic => $request->{$message}->{ItemOptionalFields}->{BibliographicDescription}->{ElectronicResource}
416         };
417
418         if ($self->{config}->{items}->{use_precats}) {
419             # We only need to create a precat copy.
420             $item = $self->create_precat_copy($item_info);
421         } else {
422             # We have to create a "partial" bib record, a call number and a copy.
423             $item = $self->create_fuller_copy($item_info);
424         }
425
426         # If we failed to create the copy, report a problem.
427         unless ($item) {
428             $response->problem(
429                 {
430                     ProblemType => 'Temporary Processing Failure',
431                     ProblemDetail => 'Failed to create the item in the system',
432                     ProblemElement => $item_idfield,
433                     ProblemValue => $item_barcode
434                 }
435             );
436             return $response;
437         }
438
439         # We try to find the pickup location in our database. It's OK
440         # if it does not exist, the user's home library will be used
441         # instead.
442         my $location = $request->{$message}->{PickupLocation};
443         if ($location) {
444             $location = $self->retrieve_org_unit_by_shortname($location);
445         }
446
447         # Now, we place the hold on the newly created copy on behalf
448         # of the patron retrieved above.
449         my $hold = $self->place_hold($item, $user, $location);
450         if (ref($hold) eq 'NCIP::Problem') {
451             $response->problem($hold);
452             return $response;
453         }
454
455         # We return the RequestId and optionally, the ItemID. We'll
456         # just return what was sent to us, since we ignored all of it
457         # but the barcode.
458         my $data = {};
459         $data->{RequestId} = NCIP::RequestId->new(
460             {
461                 AgencyId => $request->{$message}->{RequestId}->{AgencyId},
462                 RequestIdentifierType => $request->{$message}->{RequestId}->{RequestIdentifierType},
463                 RequestIdentifierValue => $request->{$message}->{RequestId}->{RequestIdentifierValue}
464             }
465         );
466         $data->{ItemId} = NCIP::Item::Id->new(
467             {
468                 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
469                 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
470                 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
471             }
472         );
473         $response->data($data);
474
475     } else {
476         my $problem = NCIP::Problem->new();
477         $problem->ProblemType('Unauthorized Combination Of Element Values For System');
478         $problem->ProblemDetail('We only support Hold For Pickup');
479         $problem->ProblemElement('RequestedActionType');
480         $problem->ProblemValue($request->{$message}->{RequestedActionType});
481         $response->problem($problem);
482     }
483
484     return $response;
485 }
486
487 =head2 checkinitem
488
489     $response = $ils->checkinitem($request);
490
491 Checks the item in if we can find the barcode in the message. It
492 returns problems if it cannot find the item in the system or if the
493 item is not checked out.
494
495 It could definitely use some more brains at some point as it does not
496 fully support everything that the standard allows. It also does not
497 really check if the checkin succeeded or not.
498
499 =cut
500
501 sub checkinitem {
502     my $self = shift;
503     my $request = shift;
504
505     # Check our session and login if necessary:
506     $self->login() unless ($self->checkauth());
507
508     # Common stuff:
509     my $message = $self->parse_request_type($request);
510     my $response = NCIP::Response->new({type => $message . 'Response'});
511     $response->header($self->make_header($request));
512
513     # We need the copy barcode from the message.
514     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
515     if (ref($item_barcode) eq 'NCIP::Problem') {
516         $response->problem($item_barcode);
517         return $response;
518     }
519
520     # Retrieve the copy details.
521     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
522     unless ($details) {
523         # Return an Unkown Item problem unless we find the copy.
524         $response->problem(
525             NCIP::Problem->new(
526                 {
527                     ProblemType => 'Unknown Item',
528                     ProblemDetail => "Item with barcode $item_barcode is not known.",
529                     ProblemElement => $item_idfield,
530                     ProblemValue => $item_barcode
531                 }
532             )
533         );
534         return $response;
535     }
536
537     # Check if a UserId was provided. If so, this is the patron to
538     # whom the copy should be checked out.
539     my $user;
540     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
541     # We ignore the problem, because the UserId is optional.
542     if (ref($user_barcode) ne 'NCIP::Problem') {
543         $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
544         # We don't ignore a problem here, however.
545         if (ref($user) eq 'NCIP::Problem') {
546             $response->problem($user);
547             return $response;
548         }
549     }
550
551     # Isolate the copy.
552     my $copy = $details->{copy};
553
554     # Look for a circulation and examine its information:
555     my $circ = $details->{circ};
556
557     # Check the circ details to see if the copy is checked out and, if
558     # the patron was provided, that it is checked out to the patron in
559     # question. We also verify the copy ownership and circulation
560     # location.
561     my $problem = $self->check_circ_details($circ, $copy, $user);
562     if ($problem) {
563         # We need to fill in some information, however.
564         if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
565             $problem->ProblemValue($user_barcode);
566             $problem->ProblemElement($user_idfield);
567         } elsif (!$problem->ProblemElement()) {
568             $problem->ProblemElement($item_idfield);
569         }
570         $response->problem($problem);
571         return $response;
572     }
573
574     # Checkin parameters. We want to skip hold targeting or making
575     # transits, to force the checkin despite the copy status, as
576     # well as void overdues.
577     my $params = {
578         barcode => $copy->barcode(),
579         force => 1,
580         noop => 1,
581         void_overdues => 1
582     };
583     my $result = $U->simplereq(
584         'open-ils.circ',
585         'open-ils.circ.checkin.override',
586         $self->{session}->{authtoken},
587         $params
588     );
589     if ($result->{textcode} eq 'SUCCESS') {
590         # Delete the copy. Since delete_copy checks ownership
591         # before attempting to delete the copy, we don't bother
592         # checking who owns it.
593         $self->delete_copy($copy);
594     }
595
596     # We should check for errors here, but I'll leave that for
597     # later.
598
599     # We need the circulation user for the information below, so we retrieve it.
600     my $circ_user = $self->retrieve_user_by_id($circ->usr());
601     my $data = {
602         ItemId => NCIP::Item::Id->new(
603             {
604                 AgencyId => $request->{$message}->{ItemId}->{AgencyId},
605                 ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
606                 ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
607             }
608         ),
609         UserId => NCIP::User::Id->new(
610             {
611                 UserIdentifierType => 'Barcode Id',
612                 UserIdentifierValue => $circ_user->card->barcode()
613             }
614         )
615     };
616
617     $response->data($data);
618
619     # At some point in the future, we should probably check if
620     # they requested optional user or item elements and return
621     # those. For the time being, we ignore those at the risk of
622     # being considered non-compliant.
623
624     return $response
625 }
626
627 =head2 renewitem
628
629     $response = $ils->renewitem($request);
630
631 Handle the RenewItem message.
632
633 =cut
634
635 sub renewitem {
636     my $self = shift;
637     my $request = shift;
638
639     # Check our session and login if necessary:
640     $self->login() unless ($self->checkauth());
641
642     # Common stuff:
643     my $message = $self->parse_request_type($request);
644     my $response = NCIP::Response->new({type => $message . 'Response'});
645     $response->header($self->make_header($request));
646
647     # We need the copy barcode from the message.
648     my ($item_barcode, $item_idfield) = $self->find_item_barcode($request);
649     if (ref($item_barcode) eq 'NCIP::Problem') {
650         $response->problem($item_barcode);
651         return $response;
652     }
653
654     # Retrieve the copy details.
655     my $details = $self->retrieve_copy_details_by_barcode($item_barcode);
656     unless ($details) {
657         # Return an Unkown Item problem unless we find the copy.
658         $response->problem(
659             NCIP::Problem->new(
660                 {
661                     ProblemType => 'Unknown Item',
662                     ProblemDetail => "Item with barcode $item_barcode is not known.",
663                     ProblemElement => $item_idfield,
664                     ProblemValue => $item_barcode
665                 }
666             )
667         );
668         return $response;
669     }
670
671     # User is required for RenewItem.
672     my ($user_barcode, $user_idfield) = $self->find_user_barcode($request);
673     if (ref($user_barcode) eq 'NCIP::Problem') {
674         $response->problem($user_barcode);
675         return $response;
676     }
677     my $user = $self->retrieve_user_by_barcode($user_barcode, $user_idfield);
678     if (ref($user) eq 'NCIP::Problem') {
679         $response->problem($user);
680         return $response;
681     }
682
683     # Isolate the copy.
684     my $copy = $details->{copy};
685
686     # Look for a circulation and examine its information:
687     my $circ = $details->{circ};
688
689     # Check the circ details to see if the copy is checked out and, if
690     # the patron was provided, that it is checked out to the patron in
691     # question. We also verify the copy ownership and circulation
692     # location.
693     my $problem = $self->check_circ_details($circ, $copy, $user);
694     if ($problem) {
695         # We need to fill in some information, however.
696         if (!$problem->ProblemValue() && !$problem->ProblemElement()) {
697             $problem->ProblemValue($user_barcode);
698             $problem->ProblemElement($user_idfield);
699         } elsif (!$problem->ProblemElement()) {
700             $problem->ProblemElement($item_idfield);
701         }
702         $response->problem($problem);
703         return $response;
704     }
705
706     # Check if user is blocked from renewals:
707     $problem = $self->check_user_for_problems($user, 'RENEW');
708     if ($problem) {
709         # Replace the ProblemElement and ProblemValue fields.
710         $problem->ProblemElement($user_idfield);
711         $problem->ProblemValue($user_barcode);
712         $response->problem($problem);
713         return $response;
714     }
715
716     # Check if the duration rule allows renewals. It should have been
717     # fleshed during the copy details retrieve.
718     my $rule = $circ->duration_rule();
719     unless (ref($rule)) {
720         $rule = $U->simplereq(
721             'open-ils.pcrud',
722             'open-ils.pcrud.retrieve.crcd',
723             $self->{session}->{authtoken},
724             $rule
725         )->gather(1);
726     }
727     if ($rule->max_renewals() < 1) {
728         $response->problem(
729             NCIP::Problem->new(
730                 {
731                     ProblemType => 'Item Not Renewable',
732                     ProblemDetail => 'Item may not be renewed.',
733                     ProblemElement => $item_idfield,
734                     ProblemValue => $item_barcode
735                 }
736             )
737         );
738         return $response;
739     }
740
741     # Check if there are renewals remaining on the latest circ:
742     if ($circ->renewal_remaining() < 1) {
743         $response->problem(
744             NCIP::Problem->new(
745                 {
746                     ProblemType => 'Maximum Renewals Exceeded',
747                     ProblemDetail => 'Renewal cannot proceed because the User has already renewed the Item the maximum number of times permitted.',
748                     ProblemElement => $item_idfield,
749                     ProblemValue => $item_barcode
750                 }
751             )
752         );
753         return $response;
754     }
755
756     # Now, we attempt the renewal. If it fails, we simply say that the
757     # user is not allowed to renew this item, without getting into
758     # details.
759     my $params = {
760         copy => $copy,
761         patron_id => $user->id(),
762         sip_renewal => 1
763     };
764     my $r = $U->simplereq(
765         'open-ils.circ',
766         'open-ils.circ.renew.override',
767         $self->{session}->{authtoken},
768         $params
769     )->gather(1);
770
771     # We only look at the first one, since more than one usually means
772     # failure.
773     if (ref($r) eq 'ARRAY') {
774         $r = $r->[0];
775     }
776     if ($r->{textcode} ne 'SUCCESS') {
777         $problem = _problem_from_event('Renewal Failed', $r);
778         $response->problem($problem);
779     } else {
780         my $data = {
781             ItemId => NCIP::Item::Id->new(
782                 {
783                     AgencyId => $request->{$message}->{ItemId}->{AgencyId},
784                     ItemIdentifierType => $request->{$message}->{ItemId}->{ItemIdentifierType},
785                     ItemIdentifierValue => $request->{$message}->{ItemId}->{ItemIdentifierValue}
786                 }
787             ),
788             UserId => NCIP::User::Id->new(
789                 {
790                     UserIdentifierType => 'Barcode Id',
791                     UserIdentifierValue => $user->card->barcode()
792                 }
793             )
794         };
795         # We need to retrieve the copy details again to refresh our
796         # circ information to get the new due date.
797         $details = $self->retrieve_copy_details_by_barcode($item_barcode);
798         $circ = $details->{circ};
799         my $due = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date()));
800         $due->set_timezone('UTC');
801         $data->{DateDue} = $due->iso8601();
802
803         $response->data($data);
804     }
805
806     # At some point in the future, we should probably check if
807     # they requested optional user or item elements and return
808     # those. For the time being, we ignore those at the risk of
809     # being considered non-compliant.
810
811     return $response;
812 }
813
814 =head1 METHODS USEFUL to SUBCLASSES
815
816 =head2 login
817
818     $ils->login();
819
820 Login to Evergreen via OpenSRF. It uses internal state from the
821 configuration file to login.
822
823 =cut
824
825 # Login via OpenSRF to Evergreen.
826 sub login {
827     my $self = shift;
828
829     # Get the authentication seed.
830     my $seed = $U->simplereq(
831         'open-ils.auth',
832         'open-ils.auth.authenticate.init',
833         $self->{config}->{credentials}->{username}
834     );
835
836     # Actually login.
837     if ($seed) {
838         my $response = $U->simplereq(
839             'open-ils.auth',
840             'open-ils.auth.authenticate.complete',
841             {
842                 username => $self->{config}->{credentials}->{username},
843                 password => md5_hex(
844                     $seed . md5_hex($self->{config}->{credentials}->{password})
845                 ),
846                 type => 'staff',
847                 workstation => $self->{config}->{credentials}->{workstation}
848             }
849         );
850         if ($response) {
851             $self->{session}->{authtoken} = $response->{payload}->{authtoken};
852             $self->{session}->{authtime} = $response->{payload}->{authtime};
853
854             # Set/reset the work_ou and user data in case something changed.
855
856             # Retrieve the work_ou as an object.
857             $self->{session}->{work_ou} = $U->simplereq(
858                 'open-ils.pcrud',
859                 'open-ils.pcrud.search.aou',
860                 $self->{session}->{authtoken},
861                 {shortname => $self->{config}->{credentials}->{work_ou}}
862             );
863
864             # We need the user information in order to do some things.
865             $self->{session}->{user} = $U->check_user_session($self->{session}->{authtoken});
866
867         }
868     }
869 }
870
871 =head2 checkauth
872
873     $valid = $ils->checkauth();
874
875 Returns 1 if the object a 'valid' authtoken, 0 if not.
876
877 =cut
878
879 sub checkauth {
880     my $self = shift;
881
882     # We use AppUtils to do the heavy lifting.
883     if (defined($self->{session})) {
884         if ($U->check_user_session($self->{session}->{authtoken})) {
885             return 1;
886         } else {
887             return 0;
888         }
889     }
890
891     # If we reach here, we don't have a session, so we are definitely
892     # not logged in.
893     return 0;
894 }
895
896 =head2 retrieve_user_by_barcode
897
898     $user = $ils->retrieve_user_by_barcode($user_barcode, $user_idfield);
899
900 Do a fleshed retrieve of a patron by barcode. Return the patron if
901 found and valid. Return a NCIP::Problem of 'Unknown User' otherwise.
902
903 The id field argument is used for the ProblemElement field in the
904 NCIP::Problem object.
905
906 An invalid patron is one where the barcode is not found in the
907 database, the patron is deleted, or the barcode used to retrieve the
908 patron is not active. The problem element is also returned if an error
909 occurs during the retrieval.
910
911 =cut
912
913 sub retrieve_user_by_barcode {
914     my ($self, $barcode, $idfield) = @_;
915     my $result = $U->simplereq(
916         'open-ils.actor',
917         'open-ils.actor.user.fleshed.retrieve_by_barcode',
918         $self->{session}->{authtoken},
919         $barcode,
920         1
921     );
922
923     # Check for a failure, or a deleted, inactive, or expired user,
924     # and if so, return empty userdata.
925     if (!$result || $U->event_code($result) || $U->is_true($result->deleted())
926             || !grep {$_->barcode() eq $barcode && $U->is_true($_->active())} @{$result->cards()}) {
927
928         my $problem = NCIP::Problem->new();
929         $problem->ProblemType('Unknown User');
930         $problem->ProblemDetail("User with barcode $barcode unknown");
931         $problem->ProblemElement($idfield);
932         $problem->ProblemValue($barcode);
933         $result = $problem;
934     }
935
936     return $result;
937 }
938
939 =head2 retrieve_user_by_id
940
941     $user = $ils->retrieve_user_by_id($id);
942
943 Similar to C<retrieve_user_by_barcode> but takes the user's database
944 id rather than barcode. This is useful when you have a circulation or
945 hold and need to get information about the user's involved in the hold
946 or circulaiton.
947
948 It returns a fleshed user on success or undef on failure.
949
950 =cut
951
952 sub retrieve_user_by_id {
953     my ($self, $id) = @_;
954
955     # Do a fleshed retrieve of the patron, and flesh the fields that
956     # we would normally use.
957     my $result = $U->simplereq(
958         'open-ils.actor',
959         'open-ils.actor.user.fleshed.retrieve',
960         $self->{session}->{authtoken},
961         $id,
962         [ 'card', 'cards', 'standing_penalties', 'addresses', 'home_ou' ]
963     );
964     # Check for an error.
965     undef($result) if ($result && $U->event_code($result));
966
967     return $result;
968 }
969
970 =head2 check_user_for_problems
971
972     $problem = $ils>check_user_for_problems($user, 'HOLD, 'CIRC', 'RENEW');
973
974 This function checks if a user has a blocked profile or any from a
975 list of provided blocks. If it does, then a NCIP::Problem object is
976 returned, otherwise an undefined value is returned.
977
978 The list of blocks appears as additional arguments after the user. You
979 can provide any value(s) that might appear in a standing penalty block
980 lit in Evergreen. The example above checks for HOLD, CIRC, and
981 RENEW. Any number of such values can be provided. If none are
982 provided, the function only checks if the patron's profiles appears in
983 the object's blocked profiles list.
984
985 It stops on the first matching block, if any.
986
987 =cut
988
989 sub check_user_for_problems {
990     my $self = shift;
991     my $user = shift;
992     my @blocks = @_;
993
994     # Fill this in if we have a problem, otherwise just return it.
995     my $problem;
996
997     # First, check the user's profile.
998     if (grep {$_->id() == $user->profile()} @{$self->{blocked_profiles}}) {
999         $problem = NCIP::Problem->new(
1000             {
1001                 ProblemType => 'User Blocked',
1002                 ProblemDetail => 'User blocked from inter-library loan',
1003                 ProblemElement => 'NULL',
1004                 ProblemValue => 'NULL'
1005             }
1006         );
1007     }
1008
1009     # Next, check if the patron has one of the indicated blocks.
1010     unless ($problem) {
1011         foreach my $block (@blocks) {
1012             if (grep {$_->standing_penalty->block_list() =~ /$block/} @{$user->standing_penalties()}) {
1013                 $problem = NCIP::Problem->new(
1014                     {
1015                         ProblemType => 'User Blocked',
1016                         ProblemDetail => 'User blocked from ' .
1017                             ($block eq 'HOLD') ? 'holds' : (($block eq 'RENEW') ? 'renewals' :
1018                                                                 (($block eq 'CIRC') ? 'checkout' : lc($block))),
1019                         ProblemElement => 'NULL',
1020                         ProblemValue => 'NULL'
1021                     }
1022                 );
1023                 last;
1024             }
1025         }
1026     }
1027
1028     return $problem;
1029 }
1030
1031 =head2 check_circ_details
1032
1033     $problem = $ils->check_circ_details($circ, $copy, $user);
1034
1035 Checks if we can checkin or renew a circulation. That is, the
1036 circulation is still open (i.e. the copy is still checked out), if we
1037 either own the copy or are the circulation location, and if the
1038 circulation is for the optional $user argument. $circ and $copy are
1039 required. $user is optional.
1040
1041 Returns a problem if any of the above conditions fail. Returns undef
1042 if they pass and we can proceed with the checkin or renewal.
1043
1044 If the failure occurred on the copy-related checks, then the
1045 ProblemElement field will be undefined and needs to be filled in with
1046 the item id field name. If the check for the copy being checked out to
1047 the provided user fails, then both ProblemElement and ProblemValue
1048 fields will be empty and need to be filled in by the caller.
1049
1050 =cut
1051
1052 sub check_circ_details {
1053     my ($self, $circ, $copy, $user) = @_;
1054
1055     # Shortcut for the next check.
1056     my $ou_id = $self->{session}->{work_ou}->id();
1057
1058     if (!$circ || $circ->checkin_time() || ($circ->circ_lib() != $ou_id && $copy->circ_lib() != $ou_id)) {
1059         # Item isn't checked out.
1060         return NCIP::Problem->new(
1061             {
1062                 ProblemType => 'Item Not Checked Out',
1063                 ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out.',
1064                 ProblemValue => $copy->barcode()
1065             }
1066         );
1067     } else {
1068         # Get data on the patron who has it checked out.
1069         my $circ_user = $self->retrieve_user_by_id($circ->usr());
1070         if ($user && $circ_user && $user->id() != $circ_user->id()) {
1071             # The ProblemElement and ProblemValue field need to be
1072             # filled in by the caller.
1073             return NCIP::Problem->new(
1074                 {
1075                     ProblemType => 'Item Not Checked Out To This User',
1076                     ProblemDetail => 'Item with barcode ' . $copy->barcode() . ' is not checked out to this user.',
1077                 }
1078             );
1079         }
1080     }
1081     # If we get here, we're good to go.
1082     return undef;
1083 }
1084
1085 =head2 retrieve_copy_details_by_barcode
1086
1087     $copy = $ils->retrieve_copy_details_by_barcode($copy_barcode);
1088
1089 Look up and retrieve some copy details by the copy barcode. This
1090 method returns either a hashref with the copy details or undefined if
1091 no copy exists with that barcode or if some error occurs.
1092
1093 The hashref has the fields copy, hold, transit, circ, volume, and mvr.
1094
1095 This method differs from C<retrieve_user_by_barcode> in that a copy
1096 cannot be invalid if it exists and it is not always an error if no
1097 copy exists. In some cases, when handling AcceptItem, we might prefer
1098 there to be no copy.
1099
1100 =cut
1101
1102 sub retrieve_copy_details_by_barcode {
1103     my $self = shift;
1104     my $barcode = shift;
1105
1106     my $copy = $U->simplereq(
1107         'open-ils.circ',
1108         'open-ils.circ.copy_details.retrieve.barcode',
1109         $self->{session}->{authtoken},
1110         $barcode
1111     );
1112
1113     # If $copy is an event, return undefined.
1114     if ($copy && $U->event_code($copy)) {
1115         undef($copy);
1116     }
1117
1118     return $copy;
1119 }
1120
1121 =head2 retrieve_org_unit_by_shortname
1122
1123     $org_unit = $ils->retrieve_org_unit_by_shortname($shortname);
1124
1125 Retrieves an org. unit from the database by shortname. Returns the
1126 org. unit as a Fieldmapper object or undefined.
1127
1128 =cut
1129
1130 sub retrieve_org_unit_by_shortname {
1131     my $self = shift;
1132     my $shortname = shift;
1133
1134     my $aou = $U->simplereq(
1135         'open-ils.pcrud',
1136         'open-ils.pcrud.search.aou',
1137         $self->{session}->{authtoken},
1138         {shortname => {'=' => {transform => 'lower', value => ['lower', $shortname]}}}
1139     );
1140
1141     return $aou;
1142 }
1143
1144 =head2 create_precat_copy
1145
1146     $item_info->{
1147         barcode => '312340123456789',
1148         author => 'Public, John Q.',
1149         title => 'Magnum Opus',
1150         call_number => '005.82',
1151         publisher => 'Brick House',
1152         publication_date => '2014'
1153     };
1154
1155     $item = $ils->create_precat_copy($item_info);
1156
1157
1158 Create a "precat" copy to use for the incoming item using a hashref of
1159 item information. At a minimum, the barcode, author and title fields
1160 need to be filled in. The other fields are ignored if provided.
1161
1162 This method is called by the AcceptItem handler if the C<use_precats>
1163 configuration option is turned on.
1164
1165 =cut
1166
1167 sub create_precat_copy {
1168     my $self = shift;
1169     my $item_info = shift;
1170
1171     my $item = Fieldmapper::asset::copy->new();
1172     $item->barcode($item_info->{barcode});
1173     $item->call_number(OILS_PRECAT_CALL_NUMBER);
1174     $item->dummy_title($item_info->{title});
1175     $item->dummy_author($item_info->{author});
1176     $item->circ_lib($self->{session}->{work_ou}->id());
1177     $item->circulate('t');
1178     $item->holdable('t');
1179     $item->opac_visible('f');
1180     $item->deleted('f');
1181     $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1182     $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1183     $item->location(1);
1184     $item->status(0);
1185     $item->editor($self->{session}->{user}->id());
1186     $item->creator($self->{session}->{user}->id());
1187     $item->isnew(1);
1188
1189     # Actually create it:
1190     my $xact;
1191     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1192     $ses->connect();
1193     eval {
1194         $xact = $ses->request(
1195             'open-ils.pcrud.transaction.begin',
1196             $self->{session}->{authtoken}
1197         )->gather(1);
1198         $item = $ses->request(
1199             'open-ils.pcrud.create.acp',
1200             $self->{session}->{authtoken},
1201             $item
1202         )->gather(1);
1203         $xact = $ses->request(
1204             'open-ils.pcrud.transaction.commit',
1205             $self->{session}->{authtoken}
1206         )->gather(1);
1207     };
1208     if ($@) {
1209         undef($item);
1210         if ($xact) {
1211             eval {
1212                 $ses->request(
1213                     'open-ils.pcrud.transaction.rollback',
1214                     $self->{session}->{authtoken}
1215                 )->gather(1);
1216             };
1217         }
1218     }
1219     $ses->disconnect();
1220
1221     return $item;
1222 }
1223
1224 =head2 create_fuller_copy
1225
1226     $item_info->{
1227         barcode => '31234003456789',
1228         author => 'Public, John Q.',
1229         title => 'Magnum Opus',
1230         call_number => '005.82',
1231         publisher => 'Brick House',
1232         publication_date => '2014'
1233     };
1234
1235     $item = $ils->create_fuller_copy($item_info);
1236
1237 Creates a skeletal bibliographic record, call number, and copy for the
1238 incoming item using a hashref with item information in it. At a
1239 minimum, the barcode, author, title, and call_number fields must be
1240 filled in.
1241
1242 This method is used by the AcceptItem handler if the C<use_precats>
1243 configuration option is NOT set.
1244
1245 =cut
1246
1247 sub create_fuller_copy {
1248     my $self = shift;
1249     my $item_info = shift;
1250
1251     my $item;
1252
1253     # We do everything in one transaction, because it should be atomic.
1254     my $ses = OpenSRF::AppSession->create('open-ils.pcrud');
1255     $ses->connect();
1256     my $xact;
1257     eval {
1258         $xact = $ses->request(
1259             'open-ils.pcrud.transaction.begin',
1260             $self->{session}->{authtoken}
1261         )->gather(1);
1262     };
1263     if ($@) {
1264         undef($xact);
1265     }
1266
1267     # The rest depends on there being a transaction.
1268     if ($xact) {
1269
1270         # Create the MARC record.
1271         my $record = MARC::Record->new();
1272         $record->encoding('UTF-8');
1273         $record->leader('00881nam a2200193   4500');
1274         my $datespec = strftime("%Y%m%d%H%M%S.0", localtime);
1275         my @fields = ();
1276         push(@fields, MARC::Field->new('005', $datespec));
1277         push(@fields, MARC::Field->new('082', '0', '4', 'a' => $item_info->{call_number}));
1278         push(@fields, MARC::Field->new('245', '0', '0', 'a' => $item_info->{title}));
1279         # Publisher is a little trickier:
1280         if ($item_info->{publisher}) {
1281             my $pub = MARC::Field->new('260', ' ', ' ', 'a' => '[S.l.]', 'b' => $item_info->{publisher});
1282             $pub->add_subfields('c' => $item_info->{publication_date}) if ($item_info->{publication_date});
1283             push(@fields, $pub);
1284         }
1285         # We have no idea if the author is personal corporate or something else, so we use a 720.
1286         push(@fields, MARC::Field->new('720', ' ', ' ', 'a' => $item_info->{author}, '4' => 'aut'));
1287         $record->append_fields(@fields);
1288         my $marc = clean_marc($record);
1289
1290         # Create the bib object.
1291         my $bib = Fieldmapper::biblio::record_entry->new();
1292         $bib->creator($self->{session}->{user}->id());
1293         $bib->editor($self->{session}->{user}->id());
1294         $bib->source($self->{bib_source}->id());
1295         $bib->active('t');
1296         $bib->deleted('f');
1297         $bib->marc($marc);
1298         $bib->isnew(1);
1299
1300         eval {
1301             $bib = $ses->request(
1302                 'open-ils.pcrud.create.bre',
1303                 $self->{session}->{authtoken},
1304                 $bib
1305             )->gather(1);
1306         };
1307         if ($@) {
1308             undef($bib);
1309             eval {
1310                 $ses->request(
1311                     'open-ils.pcrud.transaction.rollback',
1312                     $self->{session}->{authtoken}
1313                 )->gather(1);
1314             };
1315         }
1316
1317         # Create the call number
1318         my $acn;
1319         if ($bib) {
1320             $acn = Fieldmapper::asset::call_number->new();
1321             $acn->creator($self->{session}->{user}->id());
1322             $acn->editor($self->{session}->{user}->id());
1323             $acn->label($item_info->{call_number});
1324             $acn->record($bib->id());
1325             $acn->owning_lib($self->{session}->{work_ou}->id());
1326             $acn->deleted('f');
1327             $acn->isnew(1);
1328
1329             eval {
1330                 $acn = $ses->request(
1331                     'open-ils.pcrud.create.acn',
1332                     $self->{session}->{authtoken},
1333                     $acn
1334                 )->gather(1);
1335             };
1336             if ($@) {
1337                 undef($acn);
1338                 eval {
1339                     $ses->request(
1340                         'open-ils.pcrud.transaction.rollback',
1341                         $self->{session}->{authtoken}
1342                     )->gather(1);
1343                 };
1344             }
1345         }
1346
1347         # create the copy
1348         if ($acn) {
1349             $item = Fieldmapper::asset::copy->new();
1350             $item->barcode($item_info->{barcode});
1351             $item->call_number($acn->id());
1352             $item->circ_lib($self->{session}->{work_ou}->id);
1353             $item->circulate('t');
1354             if ($self->{config}->{items}->{use_force_holds}) {
1355                 $item->holdable('f');
1356             } else {
1357                 $item->holdable('t');
1358             }
1359             $item->opac_visible('f');
1360             $item->deleted('f');
1361             $item->fine_level(OILS_PRECAT_COPY_FINE_LEVEL);
1362             $item->loan_duration(OILS_PRECAT_COPY_LOAN_DURATION);
1363             $item->location(1);
1364             $item->status(0);
1365             $item->editor($self->{session}->{user}->id);
1366             $item->creator($self->{session}->{user}->id);
1367             $item->isnew(1);
1368
1369             eval {
1370                 $item = $ses->request(
1371                     'open-ils.pcrud.create.acp',
1372                     $self->{session}->{authtoken},
1373                     $item
1374                 )->gather(1);
1375
1376                 # Cross our fingers and commit the work.
1377                 $xact = $ses->request(
1378                     'open-ils.pcrud.transaction.commit',
1379                     $self->{session}->{authtoken}
1380                 )->gather(1);
1381             };
1382             if ($@) {
1383                 undef($item);
1384                 eval {
1385                     $ses->request(
1386                         'open-ils.pcrud.transaction.rollback',
1387                         $self->{session}->{authtoken}
1388                     )->gather(1) if ($xact);
1389                 };
1390             }
1391         }
1392     }
1393
1394     # We need to disconnect our session.
1395     $ses->disconnect();
1396
1397     # Now, we handle our asset stat_cat entries.
1398     if ($item) {
1399         # It would be nice to do these in the above transaction, but
1400         # pcrud does not support the ascecm object, yet.
1401         foreach my $entry (@{$self->{stat_cat_entries}}) {
1402             my $map = Fieldmapper::asset::stat_cat_entry_copy_map->new();
1403             $map->isnew(1);
1404             $map->stat_cat($entry->stat_cat());
1405             $map->stat_cat_entry($entry->id());
1406             $map->owning_copy($item->id());
1407             # We don't really worry if it succeeds or not.
1408             $U->simplereq(
1409                 'open-ils.circ',
1410                 'open-ils.circ.stat_cat.asset.copy_map.create',
1411                 $self->{session}->{authtoken},
1412                 $map
1413             );
1414         }
1415     }
1416
1417     return $item;
1418 }
1419
1420 =head2 place_hold
1421
1422     $hold = $ils->place_hold($item, $user, $location);
1423
1424 This function places a hold on $item for $user for pickup at
1425 $location. If location is not provided or undefined, the user's home
1426 library is used as a fallback.
1427
1428 $item can be a copy (asset::copy), volume (asset::call_number), or bib
1429 (biblio::record_entry). The appropriate hold type will be placed
1430 depending on the object.
1431
1432 On success, the method returns the object representing the hold. On
1433 failure, a NCIP::Problem object, describing the failure, is returned.
1434
1435 =cut
1436
1437 sub place_hold {
1438     my $self = shift;
1439     my $item = shift;
1440     my $user = shift;
1441     my $location = shift;
1442
1443     # If $location is undefined, use the user's home_ou, which should
1444     # have been fleshed when the user was retrieved.
1445     $location = $user->home_ou() unless ($location);
1446
1447     # $hold is the hold. $params is for the is_possible check.
1448     my ($hold, $params);
1449
1450     # Prep the hold with fields common to all hold types:
1451     $hold = Fieldmapper::action::hold_request->new();
1452     $hold->isnew(1); # Just to make sure.
1453     $hold->target($item->id());
1454     $hold->usr($user->id());
1455     $hold->pickup_lib($location->id());
1456     if (!$user->email()) {
1457         $hold->email_notify('f');
1458         $hold->phone_notify($user->day_phone()) if ($user->day_phone());
1459     } else {
1460         $hold->email_notify('t');
1461     }
1462
1463     # Ditto the params:
1464     $params = { pickup_lib => $location->id(), patronid => $user->id() };
1465
1466     if (ref($item) eq 'Fieldmapper::asset::copy') {
1467         my $type = ($self->{config}->{items}->{use_force_holds}) ? 'F' : 'C';
1468         $hold->hold_type($type);
1469         $hold->current_copy($item->id());
1470         $params->{hold_type} = $type;
1471         $params->{copy_id} = $item->id();
1472     } elsif (ref($item) eq 'Fieldmapper::asset::call_number') {
1473         $hold->hold_type('V');
1474         $params->{hold_type} = 'V';
1475         $params->{volume_id} = $item->id();
1476     } elsif (ref($item) eq 'Fieldmapper::biblio::record_entry') {
1477         $hold->hold_type('T');
1478         $params->{hold_type} = 'T';
1479         $params->{titleid} = $item->id();
1480     }
1481
1482     # Check if the hold is possible:
1483     my $r = $U->simplereq(
1484         'open-ils.circ',
1485         'open-ils.circ.title_hold.is_possible',
1486         $self->{session}->{authtoken},
1487         $params
1488     );
1489
1490     if ($r->{success}) {
1491         $hold = $U->simplereq(
1492             'open-ils.circ',
1493             'open-ils.circ.holds.create.override',
1494             $self->{session}->{authtoken},
1495             $hold
1496         );
1497         if (ref($hold) eq 'HASH') {
1498             $hold = _problem_from_event('Request Not Possible', $hold);
1499         }
1500     } elsif ($r->{last_event}) {
1501         $hold = _problem_from_event('Request Not Possible', $r->{last_event});
1502     } elsif ($r->{text_code}) {
1503         $hold = _problem_from_event('Request Not Possible', $r);
1504     } else {
1505         $hold = _problem_from_event('Request Not Possible');
1506     }
1507
1508     return $hold;
1509 }
1510
1511 =head2 delete_copy
1512
1513     $ils->delete_copy($copy);
1514
1515 Deletes the copy, and if it is owned by our work_ou and not a precat,
1516 we also delete the volume and bib on which the copy depends.
1517
1518 =cut
1519
1520 sub delete_copy {
1521     my $self = shift;
1522     my $copy = shift;
1523
1524     # Shortcut for ownership checks below.
1525     my $ou_id = $self->{session}->{work_ou}->id();
1526
1527     # First, make sure the copy is not already deleted and we own it.
1528     return undef if ($U->is_true($copy->deleted()) || $copy->circ_lib() != $ou_id);
1529
1530     # If call_number was fleshed, deflesh it.
1531     if (ref($copy->call_number())) {
1532         my $cn = $copy->call_number();
1533         $copy->call_number($cn->id());
1534     }
1535
1536     # We need a transaction & connected session.
1537     my $xact;
1538     my $session = OpenSRF::AppSession->create('open-ils.pcrud');
1539     $session->connect();
1540     eval {
1541         $xact = $session->request(
1542             'open-ils.pcrud.transaction.begin',
1543             $self->{session}->{authtoken}
1544         )->gather(1);
1545     };
1546     if ($@) {
1547         undef($xact);
1548     }
1549
1550     if ($xact) {
1551         # Do the rest in one eval block.
1552         eval {
1553             # Delete the copy.
1554             my $r = $session->request(
1555                 'open-ils.pcrud.delete.acp',
1556                 $self->{session}->{authtoken},
1557                 $copy
1558             )->gather(1);
1559             # Check for volume.
1560             if ($copy->call_number() != -1) {
1561                 # Retrieve the acn object and flesh the bib.
1562                 my $acn = $session->request(
1563                     'open-ils.pcrud.retrieve.acn',
1564                     $self->{session}->{authtoken},
1565                     $copy->call_number(),
1566                     {flesh => 2, flesh_fields => {acn => ['record','copies'], bre => ['call_numbers']}}
1567                 )->gather(1);
1568                 if ($acn) {
1569                     # Check if we own the call_number.
1570                     if ($acn->owning_lib() == $ou_id) {
1571                         # check for additional copies on the acn.
1572                         my @copies = grep {$_->id() != $copy->id() && !$U->is_true($_->deleted())} @{$acn->copies()};
1573                         unless (@copies) {
1574                             # Get the bib
1575                             my $bib = $acn->record();
1576                             $r = $session->request(
1577                                 'open-ils.pcrud.delete.acn',
1578                                 $self->{session}->{authtoken},
1579                                 $acn
1580                             )->gather(1);
1581                             if ($r) {
1582                                 # Check if we created the bib.
1583                                 if ($bib->creator() == $self->{session}->{user}->id()) {
1584                                 # Check for other call numbers on the bib:
1585                                     my @vols = grep {$_->id() != $acn->id() && !$U->is_true($_->deleted())}
1586                                         @{$bib->call_numbers()};
1587                                     unless (@vols) {
1588                                         $r = $session->request(
1589                                             'open-ils.pcrud.delete.bre',
1590                                             $self->{session}->{authtoken},
1591                                             $bib
1592                                         )->gather(1);
1593                                     }
1594                                 }
1595                             }
1596                         }
1597                     }
1598                 }
1599             }
1600             $r = $session->request(
1601                 'open-ils.pcrud.transaction.commit',
1602                 $self->{session}->{authtoken}
1603             )->gather(1);
1604         };
1605         if ($@) {
1606             eval {
1607                 my $r = $session->request(
1608                     'open-ils.pcrud.transaction.rollback',
1609                     $self->{session}->{authtoken}
1610                 )->gather(1);
1611             }
1612         }
1613     }
1614
1615     $session->disconnect();
1616
1617     return undef;
1618 }
1619
1620 =head1 OVERRIDDEN PARENT METHODS
1621
1622 =head2 find_user_barcode
1623
1624 We dangerously override our parent's C<find_user_barcode> to return
1625 either the $barcode or a Problem object. In list context the barcode
1626 or problem will be the first argument and the id field, if any, will
1627 be the second. We also add a second, optional, argument to indicate a
1628 default value for the id field in the event of a failure to find
1629 anything at all. (Perl lets us get away with this.)
1630
1631 =cut
1632
1633 sub find_user_barcode {
1634     my $self = shift;
1635     my $request = shift;
1636     my $default = shift;
1637
1638     unless ($default) {
1639         my $message = $self->parse_request_type($request);
1640         if ($message eq 'LookupUser') {
1641             $default = 'AuthenticationInputData';
1642         } else {
1643             $default = 'UserIdentifierValue';
1644         }
1645     }
1646
1647     my ($value, $idfield) = $self->SUPER::find_user_barcode($request);
1648
1649     unless ($value) {
1650         $idfield = $default unless ($idfield);
1651         $value = NCIP::Problem->new();
1652         $value->ProblemType('Needed Data Missing');
1653         $value->ProblemDetail('Cannot find user barcode in message.');
1654         $value->ProblemElement($idfield);
1655         $value->ProblemValue('NULL');
1656     }
1657
1658     return (wantarray) ? ($value, $idfield) : $value;
1659 }
1660
1661 =head2 find_item_barcode
1662
1663 We do pretty much the same thing as with C<find_user_barcode> for
1664 C<find_item_barcode>.
1665
1666 =cut
1667
1668 sub find_item_barcode {
1669     my $self = shift;
1670     my $request = shift;
1671     my $default = shift || 'ItemIdentifierValue';
1672
1673     my ($value, $idfield) = $self->SUPER::find_item_barcode($request);
1674
1675     unless ($value) {
1676         $idfield = $default unless ($idfield);
1677         $value = NCIP::Problem->new();
1678         $value->ProblemType('Needed Data Missing');
1679         $value->ProblemDetail('Cannot find item barcode in message.');
1680         $value->ProblemElement($idfield);
1681         $value->ProblemValue('NULL');
1682     }
1683
1684     return (wantarray) ? ($value, $idfield) : $value;
1685 }
1686
1687 # private subroutines not meant to be used directly by subclasses.
1688 # Most have to do with setup and/or state checking of implementation
1689 # components.
1690
1691 # Find, load, and parse our configuration file:
1692 sub _configure {
1693     my $self = shift;
1694
1695     # Find the configuration file via variables:
1696     my $file = OILS_NCIP_CONFIG_DEFAULT;
1697     $file = $ENV{OILS_NCIP_CONFIG} if ($ENV{OILS_NCIP_CONFIG});
1698
1699     $self->{config} = XMLin($file, NormaliseSpace => 2,
1700                             ForceArray => ['block_profile', 'stat_cat_entry']);
1701 }
1702
1703 # Bootstrap OpenSRF::System and load the IDL.
1704 sub _bootstrap {
1705     my $self = shift;
1706
1707     my $bootstrap_config = $self->{config}->{bootstrap};
1708     OpenSRF::System->bootstrap_client(config_file => $bootstrap_config);
1709
1710     my $idl = OpenSRF::Utils::SettingsClient->new->config_value("IDL");
1711     Fieldmapper->import(IDL => $idl);
1712 }
1713
1714 # Login and then initialize some object data based on the
1715 # configuration.
1716 sub _init {
1717     my $self = shift;
1718
1719     # Login to Evergreen.
1720     $self->login();
1721
1722     # Load the barred groups as pgt objects into a blocked_profiles
1723     # list.
1724     $self->{blocked_profiles} = [];
1725     foreach (@{$self->{config}->{patrons}->{block_profile}}) {
1726         my $pgt;
1727         if (ref $_) {
1728             $pgt = $U->simplereq(
1729                 'open-ils.pcrud',
1730                 'open-ils.pcrud.retrieve.pgt',
1731                 $self->{session}->{authtoken},
1732                 $_->{grp}
1733             );
1734         } else {
1735             $pgt = $U->simplereq(
1736                 'open-ils.pcrud',
1737                 'open-ils.pcrud.search.pgt',
1738                 $self->{session}->{authtoken},
1739                 {name => $_}
1740             );
1741         }
1742         push(@{$self->{blocked_profiles}}, $pgt) if ($pgt);
1743     }
1744
1745     # Load the bib source if we're not using precats.
1746     unless ($self->{config}->{items}->{use_precats}) {
1747         # Retrieve the default
1748         $self->{bib_source} = $U->simplereq(
1749             'open-ils.pcrud',
1750             'open-ils.pcrud.retrieve.cbs',
1751             $self->{session}->{authtoken},
1752             BIB_SOURCE_DEFAULT);
1753         my $data = $self->{config}->{items}->{bib_source};
1754         if ($data) {
1755             $data = $data->[0] if (ref($data) eq 'ARRAY');
1756             my $result;
1757             if (ref $data) {
1758                 $result = $U->simplereq(
1759                     'open-ils.pcrud',
1760                     'open-ils.pcrud.retrieve.cbs',
1761                     $self->{session}->{authtoken},
1762                     $data->{cbs}
1763                 );
1764             } else {
1765                 $result = $U->simplereq(
1766                     'open-ils.pcrud',
1767                     'open-ils.pcrud.search.cbs',
1768                     $self->{session}->{authtoken},
1769                     {source => $data}
1770                 );
1771             }
1772             $self->{bib_source} = $result if ($result);
1773         }
1774     }
1775
1776     # Load the required asset.stat_cat_entries:
1777     $self->{stat_cat_entries} = [];
1778     # First, make a regex for our ou and ancestors:
1779     my $ancestors = join("|", @{$U->get_org_ancestors($self->{session}->{work_ou}->id())});
1780     my $re = qr/(?:$ancestors)/;
1781     # Get the uniq stat_cat ids from the configuration:
1782     my @cats = uniq map {$_->{stat_cat}} @{$self->{config}->{items}->{stat_cat_entry}};
1783     # Retrieve all of the fleshed stat_cats and entries for the above.
1784     my $stat_cats = $U->simplereq(
1785         'open-ils.circ',
1786         'open-ils.circ.stat_cat.asset.retrieve.batch',
1787         $self->{session}->{authtoken},
1788         @cats
1789     );
1790     foreach my $entry (@{$self->{config}->{items}->{stat_cat_entry}}) {
1791         # Must have the stat_cat attr and the name, so we must have a
1792         # reference.
1793         next unless(ref $entry);
1794         my ($stat) = grep {$_->id() == $entry->{stat_cat}} @$stat_cats;
1795         push(@{$self->{stat_cat_entries}}, grep {$_->owner() =~ $re && $_->value() eq $entry->{content}} @{$stat->entries()});
1796     }
1797 }
1798
1799 # Standalone, "helper" functions.  These do not take an object or
1800 # class reference.
1801
1802 # Check if a user is past their expiration date.
1803 sub _expired {
1804     my $user = shift;
1805     my $expired = 0;
1806
1807     # Users might not expire.  If so, they have no expire_date.
1808     if ($user->expire_date()) {
1809         my $expires = DateTime::Format::ISO8601->parse_datetime(
1810             cleanse_ISO8601($user->expire_date())
1811         )->epoch();
1812         my $now = DateTime->now()->epoch();
1813         $expired = $now > $expires;
1814     }
1815
1816     return $expired;
1817 }
1818
1819 # Creates a NCIP Problem from an event. Takes a string for the problem
1820 # type, the event hashref, and optional arguments for the
1821 # ProblemElement and ProblemValue fields.
1822 sub _problem_from_event {
1823     my ($type, $evt, $element, $value) = @_;
1824
1825     my $detail;
1826
1827     # This block will likely need to get smarter in the near future.
1828     if ($evt) {
1829         if ($evt->{text_code} eq 'PERM_FAILURE') {
1830             $detail = 'Permission Failure: ' . $evt->{ilsperm};
1831             $detail =~ s/\.override$//;
1832         } else {
1833             $detail = 'ILS returned ' . $evt->{text_code} . ' error.';
1834         }
1835     } else {
1836         $detail = 'Detail not available.';
1837     }
1838
1839     return NCIP::Problem->new(
1840         {
1841             ProblemType => $type,
1842             ProblemDetail => $detail,
1843             ProblemElement => ($element) ? $element : 'NULL',
1844             ProblemValue => ($value) ? $value : 'NULL'
1845         }
1846     );
1847 }
1848
1849 1;