1 package Koha::Illrequest;
3 # Copyright PTFS Europe 2016
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 51 Franklin
19 # Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 use File::Basename qw/basename/;
27 use Koha::Exceptions::Ill;
28 use Koha::Illrequestattributes;
33 use base qw(Koha::Object);
37 Koha::Illrequest - Koha Illrequest Object class
41 An ILLRequest consists of two parts; the Illrequest Koha::Object, and a series
42 of related Illrequestattributes.
44 The former encapsulates the basic necessary information that any ILL requires
45 to be usable in Koha. The latter is a set of additional properties used by
48 The former subsumes the legacy "Status" object. The latter remains
49 encapsulated in the "Record" object.
53 - Anything invoking the ->status method; annotated with:
54 + # Old use of ->status !
58 =head2 Backend API Response Principles
60 All methods should return a hashref in the following format:
66 This should be set to 1 if an error was encountered.
70 The status should be a string from the list of statuses detailed below.
74 The message is a free text field that can be passed on to the end user.
78 The value returned by the method.
82 =head2 Interface Status Messages
86 =item * branch_address_incomplete
88 An interface request has determined branch address details are incomplete.
90 =item * cancel_success
92 The interface's cancel_request method was successful in cancelling the
93 Illrequest using the API.
97 The interface's cancel_request method failed to cancel the Illrequest using
102 The interface's request method returned saying that the desired item is not
103 available for request.
109 =head3 illrequestattributes
113 sub illrequestattributes {
115 return Koha::Illrequestattributes->_new_from_dbic(
116 scalar $self->_result->illrequestattributes
126 return Koha::Patron->_new_from_dbic(
127 scalar $self->_result->borrowernumber
133 Require "Base.pm" from the relevant ILL backend.
138 my ( $self, $backend_id ) = @_;
140 my @raw = qw/Koha Illbackends/; # Base Path
142 my $backend_name = $backend_id || $self->backend;
144 unless ( defined $backend_name && $backend_name ne '' ) {
145 Koha::Exceptions::Ill::InvalidBackendId->throw(
146 "An invalid backend ID was requested ('')");
149 my $location = join "/", @raw, $backend_name, "Base.pm"; # File to load
150 my $backend_class = join "::", @raw, $backend_name, "Base"; # Package name
152 $self->{_my_backend} = $backend_class->new({ config => $self->_config });
159 my $backend = $abstract->_backend($new_backend);
160 my $backend = $abstract->_backend;
162 Getter/Setter for our API object.
167 my ( $self, $backend ) = @_;
168 $self->{_my_backend} = $backend if ( $backend );
169 # Dynamically load our backend object, as late as possible.
170 $self->load_backend unless ( $self->{_my_backend} );
171 return $self->{_my_backend};
174 =head3 _backend_capability
176 my $backend_capability_result = $self->_backend_capability($name, $args);
178 This is a helper method to invoke optional capabilities in the backend. If
179 the capability named by $name is not supported, return 0, else invoke it,
180 passing $args along with the invocation, and return its return value.
182 NOTE: this module suffers from a confusion in termninology:
184 in _backend_capability, the notion of capability refers to an optional feature
185 that is implemented in core, but might not be supported by a given backend.
187 in capabilities & custom_capability, capability refers to entries in the
188 status_graph (after union between backend and core).
190 The easiest way to fix this would be to fix the terminology in
191 capabilities & custom_capability and their callers.
195 sub _backend_capability {
196 my ( $self, $name, $args ) = @_;
199 $capability = $self->_backend->capabilities($name);
204 return &{$capability}($args);
212 my $config = $abstract->_config($config);
213 my $config = $abstract->_config;
215 Getter/Setter for our config object.
220 my ( $self, $config ) = @_;
221 $self->{_my_config} = $config if ( $config );
222 # Load our config object, as late as possible.
223 unless ( $self->{_my_config} ) {
224 $self->{_my_config} = Koha::Illrequest::Config->new;
226 return $self->{_my_config};
235 return $self->_backend->metadata($self);
238 =head3 _core_status_graph
240 my $core_status_graph = $illrequest->_core_status_graph;
242 Returns ILL module's default status graph. A status graph defines the list of
243 available actions at any stage in the ILL workflow. This is for instance used
244 by the perl script & template to generate the correct buttons to display to
245 the end user at any given point.
249 sub _core_status_graph {
253 prev_actions => [ ], # Actions containing buttons
254 # leading to this status
255 id => 'NEW', # ID of this status
256 name => 'New request', # UI name of this status
257 ui_method_name => 'New request', # UI name of method leading
259 method => 'create', # method to this status
260 next_actions => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all
261 # requests with this status
262 ui_method_icon => 'fa-plus', # UI Style class
265 prev_actions => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
268 ui_method_name => 'Confirm request',
270 next_actions => [ 'REQREV', 'COMP' ],
271 ui_method_icon => 'fa-check',
274 prev_actions => [ 'NEW', 'REQREV' ],
276 name => 'Requested from partners',
277 ui_method_name => 'Place request with partners',
278 method => 'generic_confirm',
279 next_actions => [ 'COMP' ],
280 ui_method_icon => 'fa-send-o',
283 prev_actions => [ 'REQ' ],
285 name => 'Request reverted',
286 ui_method_name => 'Revert Request',
288 next_actions => [ 'REQ', 'GENREQ', 'KILL' ],
289 ui_method_icon => 'fa-times',
294 name => 'Queued request',
297 next_actions => [ 'REQ', 'KILL' ],
301 prev_actions => [ 'NEW' ],
303 name => 'Cancellation requested',
306 next_actions => [ 'KILL', 'REQ' ],
310 prev_actions => [ 'REQ' ],
313 ui_method_name => 'Mark completed',
314 method => 'mark_completed',
316 ui_method_icon => 'fa-check',
319 prev_actions => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ],
322 ui_method_name => 'Delete request',
325 ui_method_icon => 'fa-trash',
330 =head3 _core_status_graph
332 my $status_graph = $illrequest->_core_status_graph($origin, $new_graph);
334 Return a new status_graph, the result of merging $origin & new_graph. This is
335 operation is a union over the sets defied by the two graphs.
337 Each entry in $new_graph is added to $origin. We do not provide a syntax for
338 'subtraction' of entries from $origin.
340 Whilst it is not intended that this works, you can override entries in $origin
341 with entries with the same key in $new_graph. This can lead to problematic
342 behaviour when $new_graph adds an entry, which modifies a dependent entry in
343 $origin, only for the entry in $origin to be replaced later with a new entry
346 NOTE: this procedure does not "re-link" entries in $origin or $new_graph,
347 i.e. each of the graphs need to be correct at the outset of the operation.
351 sub _status_graph_union {
352 my ( $self, $core_status_graph, $backend_status_graph ) = @_;
353 # Create new status graph with:
354 # - all core_status_graph
355 # - for-each each backend_status_graph
356 # + add to new status graph
357 # + for each core prev_action:
358 # * locate core_status
359 # * update next_actions with additional next action.
360 # + for each core next_action:
361 # * locate core_status
362 # * update prev_actions with additional prev action
364 my @core_status_ids = keys %{$core_status_graph};
365 my $status_graph = clone($core_status_graph);
367 foreach my $backend_status_key ( keys %{$backend_status_graph} ) {
368 my $backend_status = $backend_status_graph->{$backend_status_key};
369 # Add to new status graph
370 $status_graph->{$backend_status_key} = $backend_status;
371 # Update all core methods' next_actions.
372 foreach my $prev_action ( @{$backend_status->{prev_actions}} ) {
373 if ( grep $prev_action, @core_status_ids ) {
375 @{$status_graph->{$prev_action}->{next_actions}};
376 push @next_actions, $backend_status_key;
377 $status_graph->{$prev_action}->{next_actions}
381 # Update all core methods' prev_actions
382 foreach my $next_action ( @{$backend_status->{next_actions}} ) {
383 if ( grep $next_action, @core_status_ids ) {
385 @{$status_graph->{$next_action}->{prev_actions}};
386 push @prev_actions, $backend_status_key;
387 $status_graph->{$next_action}->{prev_actions}
393 return $status_graph;
400 my $capabilities = $illrequest->capabilities;
402 Return a hashref mapping methods to operation names supported by the queried
405 Example return value:
407 { create => "Create Request", confirm => "Progress Request" }
409 NOTE: this module suffers from a confusion in termninology:
411 in _backend_capability, the notion of capability refers to an optional feature
412 that is implemented in core, but might not be supported by a given backend.
414 in capabilities & custom_capability, capability refers to entries in the
415 status_graph (after union between backend and core).
417 The easiest way to fix this would be to fix the terminology in
418 capabilities & custom_capability and their callers.
423 my ( $self, $status ) = @_;
424 # Generate up to date status_graph
425 my $status_graph = $self->_status_graph_union(
426 $self->_core_status_graph,
427 $self->_backend->status_graph({
432 # Extract available actions from graph.
433 return $status_graph->{$status} if $status;
434 # Or return entire graph.
435 return $status_graph;
438 =head3 custom_capability
440 Return the result of invoking $CANDIDATE on this request's backend with
441 $PARAMS, or 0 if $CANDIDATE is an unknown method on backend.
443 NOTE: this module suffers from a confusion in termninology:
445 in _backend_capability, the notion of capability refers to an optional feature
446 that is implemented in core, but might not be supported by a given backend.
448 in capabilities & custom_capability, capability refers to entries in the
449 status_graph (after union between backend and core).
451 The easiest way to fix this would be to fix the terminology in
452 capabilities & custom_capability and their callers.
456 sub custom_capability {
457 my ( $self, $candidate, $params ) = @_;
458 foreach my $capability ( values %{$self->capabilities} ) {
459 if ( $candidate eq $capability->{method} ) {
461 $self->_backend->$candidate({
465 return $self->expandTemplate($response);
471 =head3 available_backends
473 Return a list of available backends.
477 sub available_backends {
479 my @backends = $self->_config->available_backends;
483 =head3 available_actions
485 Return a list of available actions.
489 sub available_actions {
491 my $current_action = $self->capabilities($self->status);
492 my @available_actions = map { $self->capabilities($_) }
493 @{$current_action->{next_actions}};
494 return \@available_actions;
497 =head3 mark_completed
499 Mark a request as completed (status = COMP).
505 $self->status('COMP')->store;
510 method => 'mark_completed',
516 =head2 backend_confirm
518 Confirm a request. The backend handles setting of mandatory fields in the commit stage:
524 =item * accessurl, cost (if available).
530 sub backend_confirm {
531 my ( $self, $params ) = @_;
533 my $response = $self->_backend->confirm({
537 return $self->expandTemplate($response);
540 =head3 backend_update_status
544 sub backend_update_status {
545 my ( $self, $params ) = @_;
546 return $self->expandTemplate($self->_backend->update_status($params));
549 =head3 backend_cancel
551 my $ILLResponse = $illRequest->backend_cancel;
553 The standard interface method allowing for request cancellation.
558 my ( $self, $params ) = @_;
560 my $result = $self->_backend->cancel({
565 return $self->expandTemplate($result);
570 my $renew_response = $illRequest->backend_renew;
572 The standard interface method allowing for request renewal queries.
578 return $self->expandTemplate(
579 $self->_backend->renew({
585 =head3 backend_create
587 my $create_response = $abstractILL->backend_create($params);
589 Return an array of Record objects created by querying our backend with
592 In the context of the other ILL methods, this is a special method: we only
593 pass it $params, as it does not yet have any other data associated with it.
598 my ( $self, $params ) = @_;
600 # Establish whether we need to do a generic copyright clearance.
601 if ( ( !$params->{stage} || $params->{stage} eq 'init' )
602 && C4::Context->preference("ILLModuleCopyrightClearance") ) {
608 stage => 'copyrightclearance',
610 backend => $self->_backend->name
613 } elsif ( defined $params->{stage}
614 && $params->{stage} eq 'copyrightclearance' ) {
615 $params->{stage} = 'init';
618 # First perform API action, then...
623 my $result = $self->_backend->create($args);
625 # ... simple case: we're not at 'commit' stage.
626 my $stage = $result->{stage};
627 return $self->expandTemplate($result)
628 unless ( 'commit' eq $stage );
630 # ... complex case: commit!
632 # Do we still have space for an ILL or should we queue?
633 my $permitted = $self->check_limits(
634 { patron => $self->patron }, { librarycode => $self->branchcode }
637 # Now augment our committed request.
639 $result->{permitted} = $permitted; # Queue request?
643 # ...Updating status!
644 $self->status('QUEUED')->store unless ( $permitted );
646 return $self->expandTemplate($result);
649 =head3 expandTemplate
651 my $params = $abstract->expandTemplate($params);
653 Return a version of $PARAMS augmented with our required template path.
658 my ( $self, $params ) = @_;
659 my $backend = $self->_backend->name;
660 # Generate path to file to load
661 my $backend_dir = $self->_config->backend_dir;
662 my $backend_tmpl = join "/", $backend_dir, $backend;
663 my $intra_tmpl = join "/", $backend_tmpl, "intra-includes",
664 $params->{method} . ".inc";
665 my $opac_tmpl = join "/", $backend_tmpl, "opac-includes",
666 $params->{method} . ".inc";
668 $params->{template} = $intra_tmpl;
669 $params->{opac_template} = $opac_tmpl;
673 #### Abstract Imports
677 my $limit_rules = $abstract->getLimits( {
678 type => 'brw_cat' | 'branch',
682 Return the ILL limit rules for the supplied combination of type / value.
684 As the config may have no rules for this particular type / value combination,
685 or for the default, we must define fall-back values here.
690 my ( $self, $params ) = @_;
691 my $limits = $self->_config->getLimitRules($params->{type});
693 if ( defined $params->{value}
694 && defined $limits->{$params->{value}} ) {
695 return $limits->{$params->{value}};
698 return $limits->{default} || { count => -1, method => 'active' };
704 my $prefix = $abstract->getPrefix( {
706 branch => $branch_code,
709 Return the ILL prefix as defined by our $params: either per borrower category,
710 per branch or the default.
715 my ( $self, $params ) = @_;
716 my $brn_prefixes = $self->_config->getPrefixes('branch');
717 my $brw_prefixes = $self->_config->getPrefixes('brw_cat');
719 return $brw_prefixes->{$params->{brw_cat}}
720 || $brn_prefixes->{$params->{branch}}
721 || $brw_prefixes->{default}
722 || ""; # "the empty prefix"
725 #### Illrequests Imports
729 my $ok = $illRequests->check_limits( {
730 borrower => $borrower,
731 branchcode => 'branchcode' | undef,
734 Given $PARAMS, a hashref containing a $borrower object and a $branchcode,
735 see whether we are still able to place ILLs.
737 LimitRules are derived from koha-conf.xml:
738 + default limit counts, and counting method
739 + branch specific limit counts & counting method
740 + borrower category specific limit counts & counting method
741 + err on the side of caution: a counting fail will cause fail, even if
742 the other counts passes.
747 my ( $self, $params ) = @_;
748 my $patron = $params->{patron};
749 my $branchcode = $params->{librarycode} || $patron->branchcode;
751 # Establish maximum number of allowed requests
752 my ( $branch_rules, $brw_rules ) = (
759 value => $patron->categorycode,
762 my ( $branch_limit, $brw_limit )
763 = ( $branch_rules->{count}, $brw_rules->{count} );
764 # Establish currently existing requests
765 my ( $branch_count, $brw_count ) = (
766 $self->_limit_counter(
767 $branch_rules->{method}, { branchcode => $branchcode }
769 $self->_limit_counter(
770 $brw_rules->{method}, { borrowernumber => $patron->borrowernumber }
775 # A limit of -1 means no limit exists.
776 # We return blocked if either branch limit or brw limit is reached.
777 if ( ( $branch_limit != -1 && $branch_limit <= $branch_count )
778 || ( $brw_limit != -1 && $brw_limit <= $brw_count ) ) {
786 my ( $self, $method, $target ) = @_;
788 # Establish parameters of counts
790 if ($method && $method eq 'annual') {
791 $resultset = Koha::Illrequests->search({
794 \"YEAR(placed) = YEAR(NOW())"
797 } else { # assume 'active'
798 # XXX: This status list is ugly. There should be a method in config
800 my $where = { status => { -not_in => [ 'QUEUED', 'COMP' ] } };
801 $resultset = Koha::Illrequests->search({ %{$target}, %{$where} });
805 return $resultset->count;
808 =head3 requires_moderation
810 my $status = $illRequest->requires_moderation;
812 Return the name of the status if moderation by staff is required; or 0
817 sub requires_moderation {
819 my $require_moderation = {
820 'CANCREQ' => 'CANCREQ',
822 return $require_moderation->{$self->status};
825 =head3 generic_confirm
827 my $stage_summary = $illRequest->generic_confirm;
829 Handle the generic_confirm extended method. The first stage involves creating
830 a template email for the end user to edit in the browser. The second stage
831 attempts to submit the email.
835 sub generic_confirm {
836 my ( $self, $params ) = @_;
837 my $branch = Koha::Libraries->find($params->{current_branchcode})
838 || die "Invalid current branchcode. Are you logged in as the database user?";
839 if ( !$params->{stage}|| $params->{stage} eq 'init' ) {
840 my $draft->{subject} = "ILL Request";
841 $draft->{body} = <<EOF;
844 We would like to request an interlibrary loan for a title matching the
845 following description:
849 my $details = $self->metadata;
850 while (my ($title, $value) = each %{$details}) {
851 $draft->{body} .= " - " . $title . ": " . $value . "\n"
854 $draft->{body} .= <<EOF;
856 Please let us know if you are able to supply this to us.
862 my @address = map { $branch->$_ }
863 qw/ branchname branchaddress1 branchaddress2 branchaddress3
864 branchzip branchcity branchstate branchcountry branchphone
867 foreach my $line ( @address ) {
868 $address .= $line . "\n" if $line;
871 $draft->{body} .= $address;
873 my $partners = Koha::Patrons->search({
874 categorycode => $self->_config->partner_code
880 method => 'generic_confirm',
884 partners => $partners,
888 } elsif ( 'draft' eq $params->{stage} ) {
889 # Create the to header
890 my $to = $params->{partners};
892 $to =~ s/^\x00//; # Strip leading NULLs
893 $to =~ s/\x00/; /; # Replace others with '; '
895 die "No target email addresses found. Either select at least one partner or check your ILL partner library records." if ( !$to );
896 # Create the from, replyto and sender headers
897 my $from = $branch->branchemail;
898 my $replyto = $branch->branchreplyto || $from;
899 die "Your branch has no email address. Please set it."
902 my $message = Koha::Email->new;
903 my %mail = $message->create_message_headers(
908 subject => Encode::encode( "utf8", $params->{subject} ),
909 message => Encode::encode( "utf8", $params->{body} ),
910 contenttype => 'text/plain',
914 my $result = sendmail(%mail);
916 $self->status("GENREQ")->store;
921 method => 'generic_confirm',
928 status => 'email_failed',
929 message => $Mail::Sendmail::error,
930 method => 'generic_confirm',
935 die "Unknown stage, should not have happened."
941 my $prefix = $record->id_prefix;
943 Return the prefix appropriate for the current Illrequest as derived from the
944 borrower and branch associated with this request's Status, and the config
951 my $brw = $self->patron;
952 my $brw_cat = "dummy";
953 $brw_cat = $brw->categorycode
954 unless ( 'HASH' eq ref($brw) && $brw->{deleted} );
955 my $prefix = $self->getPrefix( {
957 branch => $self->branchcode,
959 $prefix .= "-" if ( $prefix );
965 my $params = $illRequest->_censor($params);
967 Return $params, modified to reflect our censorship requirements.
972 my ( $self, $params ) = @_;
973 my $censorship = $self->_config->censorship;
974 $params->{censor_notes_staff} = $censorship->{censor_notes_staff}
975 if ( $params->{opac} );
976 $params->{display_reply_date} = ( $censorship->{censor_reply_date} ) ? 0 : 1;
983 $json = $illrequest->TO_JSON
985 Overloaded I<TO_JSON> method that takes care of inserting calculated values
986 into the unblessed representation of the object.
991 my ( $self, $embed ) = @_;
993 my $object = $self->SUPER::TO_JSON();
994 $object->{id_prefix} = $self->id_prefix;
996 if ( scalar (keys %$embed) ) {
997 # Augment the request response with patron details if appropriate
998 if ( $embed->{patron} ) {
999 my $patron = $self->patron;
1000 $object->{patron} = {
1001 firstname => $patron->firstname,
1002 surname => $patron->surname,
1003 cardnumber => $patron->cardnumber
1006 # Augment the request response with metadata details if appropriate
1007 if ( $embed->{metadata} ) {
1008 $object->{metadata} = $self->metadata;
1010 # Augment the request response with status details if appropriate
1011 if ( $embed->{capabilities} ) {
1012 $object->{capabilities} = $self->capabilities;
1014 # Augment the request response with library details if appropriate
1015 if ( $embed->{branch} ) {
1016 $object->{branch} = Koha::Libraries->find(
1025 =head2 Internal methods
1032 return 'Illrequest';
1037 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>