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.
22 use File::Basename qw/basename/;
26 use Koha::Illrequestattributes;
32 use base qw(Koha::Object);
36 Koha::Illrequest - Koha Illrequest Object class
40 An ILLRequest consists of two parts; the Illrequest Koha::Object, and a series
41 of related Illrequestattributes.
43 The former encapsulates the basic necessary information that any ILL requires
44 to be usable in Koha. The latter is a set of additional properties used by
47 The former subsumes the legacy "Status" object. The latter remains
48 encapsulated in the "Record" object.
52 - Anything invoking the ->status method; annotated with:
53 + # Old use of ->status !
57 =head2 Backend API Response Principles
59 All methods should return a hashref in the following format:
65 This should be set to 1 if an error was encountered.
69 The status should be a string from the list of statuses detailed below.
73 The message is a free text field that can be passed on to the end user.
77 The value returned by the method.
81 =head2 Interface Status Messages
85 =item * branch_address_incomplete
87 An interface request has determined branch address details are incomplete.
89 =item * cancel_success
91 The interface's cancel_request method was successful in cancelling the
92 Illrequest using the API.
96 The interface's cancel_request method failed to cancel the Illrequest using
101 The interface's request method returned saying that the desired item is not
102 available for request.
108 =head3 illrequestattributes
112 sub illrequestattributes {
114 return Koha::Illrequestattributes->_new_from_dbic(
115 scalar $self->_result->illrequestattributes
125 return Koha::Patron->_new_from_dbic(
126 scalar $self->_result->borrowernumber
132 Require "Base.pm" from the relevant ILL backend.
137 my ( $self, $backend_id ) = @_;
139 my @raw = qw/Koha Illbackends/; # Base Path
141 my $backend_name = $backend_id || $self->backend;
142 my $location = join "/", @raw, $backend_name, "Base.pm"; # File to load
143 my $backend_class = join "::", @raw, $backend_name, "Base"; # Package name
145 $self->{_my_backend} = $backend_class->new({ config => $self->_config });
151 my $backend = $abstract->_backend($new_backend);
152 my $backend = $abstract->_backend;
154 Getter/Setter for our API object.
159 my ( $self, $backend ) = @_;
160 $self->{_my_backend} = $backend if ( $backend );
161 # Dynamically load our backend object, as late as possible.
162 $self->load_backend unless ( $self->{_my_backend} );
163 return $self->{_my_backend};
166 =head3 _backend_capability
168 my $backend_capability_result = $self->_backend_capability($name, $args);
170 This is a helper method to invoke optional capabilities in the backend. If
171 the capability named by $name is not supported, return 0, else invoke it,
172 passing $args along with the invocation, and return its return value.
174 NOTE: this module suffers from a confusion in termninology:
176 in _backend_capability, the notion of capability refers to an optional feature
177 that is implemented in core, but might not be supported by a given backend.
179 in capabilities & custom_capability, capability refers to entries in the
180 status_graph (after union between backend and core).
182 The easiest way to fix this would be to fix the terminology in
183 capabilities & custom_capability and their callers.
187 sub _backend_capability {
188 my ( $self, $name, $args ) = @_;
191 $capability = $self->_backend->capabilities($name);
196 return &{$capability}($args);
204 my $config = $abstract->_config($config);
205 my $config = $abstract->_config;
207 Getter/Setter for our config object.
212 my ( $self, $config ) = @_;
213 $self->{_my_config} = $config if ( $config );
214 # Load our config object, as late as possible.
215 unless ( $self->{_my_config} ) {
216 $self->{_my_config} = Koha::Illrequest::Config->new;
218 return $self->{_my_config};
227 return $self->_backend->metadata($self);
230 =head3 _core_status_graph
232 my $core_status_graph = $illrequest->_core_status_graph;
234 Returns ILL module's default status graph. A status graph defines the list of
235 available actions at any stage in the ILL workflow. This is for instance used
236 by the perl script & template to generate the correct buttons to display to
237 the end user at any given point.
241 sub _core_status_graph {
245 prev_actions => [ ], # Actions containing buttons
246 # leading to this status
247 id => 'NEW', # ID of this status
248 name => 'New request', # UI name of this status
249 ui_method_name => 'New request', # UI name of method leading
251 method => 'create', # method to this status
252 next_actions => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all
253 # requests with this status
254 ui_method_icon => 'fa-plus', # UI Style class
257 prev_actions => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
260 ui_method_name => 'Confirm request',
262 next_actions => [ 'REQREV', 'COMP' ],
263 ui_method_icon => 'fa-check',
266 prev_actions => [ 'NEW', 'REQREV' ],
268 name => 'Requested from partners',
269 ui_method_name => 'Place request with partners',
270 method => 'generic_confirm',
271 next_actions => [ 'COMP' ],
272 ui_method_icon => 'fa-send-o',
275 prev_actions => [ 'REQ' ],
277 name => 'Request reverted',
278 ui_method_name => 'Revert Request',
280 next_actions => [ 'REQ', 'GENREQ', 'KILL' ],
281 ui_method_icon => 'fa-times',
286 name => 'Queued request',
289 next_actions => [ 'REQ', 'KILL' ],
293 prev_actions => [ 'NEW' ],
295 name => 'Cancellation requested',
298 next_actions => [ 'KILL', 'REQ' ],
302 prev_actions => [ 'REQ' ],
305 ui_method_name => 'Mark completed',
306 method => 'mark_completed',
308 ui_method_icon => 'fa-check',
311 prev_actions => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ],
314 ui_method_name => 'Delete request',
317 ui_method_icon => 'fa-trash',
322 =head3 _core_status_graph
324 my $status_graph = $illrequest->_core_status_graph($origin, $new_graph);
326 Return a new status_graph, the result of merging $origin & new_graph. This is
327 operation is a union over the sets defied by the two graphs.
329 Each entry in $new_graph is added to $origin. We do not provide a syntax for
330 'subtraction' of entries from $origin.
332 Whilst it is not intended that this works, you can override entries in $origin
333 with entries with the same key in $new_graph. This can lead to problematic
334 behaviour when $new_graph adds an entry, which modifies a dependent entry in
335 $origin, only for the entry in $origin to be replaced later with a new entry
338 NOTE: this procedure does not "re-link" entries in $origin or $new_graph,
339 i.e. each of the graphs need to be correct at the outset of the operation.
343 sub _status_graph_union {
344 my ( $self, $core_status_graph, $backend_status_graph ) = @_;
345 # Create new status graph with:
346 # - all core_status_graph
347 # - for-each each backend_status_graph
348 # + add to new status graph
349 # + for each core prev_action:
350 # * locate core_status
351 # * update next_actions with additional next action.
352 # + for each core next_action:
353 # * locate core_status
354 # * update prev_actions with additional prev action
356 my @core_status_ids = keys %{$core_status_graph};
357 my $status_graph = clone($core_status_graph);
359 foreach my $backend_status_key ( keys %{$backend_status_graph} ) {
360 my $backend_status = $backend_status_graph->{$backend_status_key};
361 # Add to new status graph
362 $status_graph->{$backend_status_key} = $backend_status;
363 # Update all core methods' next_actions.
364 foreach my $prev_action ( @{$backend_status->{prev_actions}} ) {
365 if ( grep $prev_action, @core_status_ids ) {
367 @{$status_graph->{$prev_action}->{next_actions}};
368 push @next_actions, $backend_status_key;
369 $status_graph->{$prev_action}->{next_actions}
373 # Update all core methods' prev_actions
374 foreach my $next_action ( @{$backend_status->{next_actions}} ) {
375 if ( grep $next_action, @core_status_ids ) {
377 @{$status_graph->{$next_action}->{prev_actions}};
378 push @prev_actions, $backend_status_key;
379 $status_graph->{$next_action}->{prev_actions}
385 return $status_graph;
392 my $capabilities = $illrequest->capabilities;
394 Return a hashref mapping methods to operation names supported by the queried
397 Example return value:
399 { create => "Create Request", confirm => "Progress Request" }
401 NOTE: this module suffers from a confusion in termninology:
403 in _backend_capability, the notion of capability refers to an optional feature
404 that is implemented in core, but might not be supported by a given backend.
406 in capabilities & custom_capability, capability refers to entries in the
407 status_graph (after union between backend and core).
409 The easiest way to fix this would be to fix the terminology in
410 capabilities & custom_capability and their callers.
415 my ( $self, $status ) = @_;
416 # Generate up to date status_graph
417 my $status_graph = $self->_status_graph_union(
418 $self->_core_status_graph,
419 $self->_backend->status_graph({
424 # Extract available actions from graph.
425 return $status_graph->{$status} if $status;
426 # Or return entire graph.
427 return $status_graph;
430 =head3 custom_capability
432 Return the result of invoking $CANDIDATE on this request's backend with
433 $PARAMS, or 0 if $CANDIDATE is an unknown method on backend.
435 NOTE: this module suffers from a confusion in termninology:
437 in _backend_capability, the notion of capability refers to an optional feature
438 that is implemented in core, but might not be supported by a given backend.
440 in capabilities & custom_capability, capability refers to entries in the
441 status_graph (after union between backend and core).
443 The easiest way to fix this would be to fix the terminology in
444 capabilities & custom_capability and their callers.
448 sub custom_capability {
449 my ( $self, $candidate, $params ) = @_;
450 foreach my $capability ( values %{$self->capabilities} ) {
451 if ( $candidate eq $capability->{method} ) {
453 $self->_backend->$candidate({
457 return $self->expandTemplate($response);
463 =head3 available_backends
465 Return a list of available backends.
469 sub available_backends {
471 my $backend_dir = $self->_config->backend_dir;
473 @backends = glob "$backend_dir/*" if ( $backend_dir );
474 @backends = map { basename($_) } @backends;
478 =head3 available_actions
480 Return a list of available actions.
484 sub available_actions {
486 my $current_action = $self->capabilities($self->status);
487 my @available_actions = map { $self->capabilities($_) }
488 @{$current_action->{next_actions}};
489 return \@available_actions;
492 =head3 mark_completed
494 Mark a request as completed (status = COMP).
500 $self->status('COMP')->store;
505 method => 'mark_completed',
511 =head2 backend_confirm
513 Confirm a request. The backend handles setting of mandatory fields in the commit stage:
519 =item * accessurl, cost (if available).
525 sub backend_confirm {
526 my ( $self, $params ) = @_;
528 my $response = $self->_backend->confirm({
532 return $self->expandTemplate($response);
535 =head3 backend_update_status
539 sub backend_update_status {
540 my ( $self, $params ) = @_;
541 return $self->expandTemplate($self->_backend->update_status($params));
544 =head3 backend_cancel
546 my $ILLResponse = $illRequest->backend_cancel;
548 The standard interface method allowing for request cancellation.
553 my ( $self, $params ) = @_;
555 my $result = $self->_backend->cancel({
560 return $self->expandTemplate($result);
565 my $renew_response = $illRequest->backend_renew;
567 The standard interface method allowing for request renewal queries.
573 return $self->expandTemplate(
574 $self->_backend->renew({
580 =head3 backend_create
582 my $create_response = $abstractILL->backend_create($params);
584 Return an array of Record objects created by querying our backend with
587 In the context of the other ILL methods, this is a special method: we only
588 pass it $params, as it does not yet have any other data associated with it.
593 my ( $self, $params ) = @_;
595 # Establish whether we need to do a generic copyright clearance.
596 if ( ( !$params->{stage} || $params->{stage} eq 'init' )
597 && C4::Context->preference("ILLModuleCopyrightClearance") ) {
603 stage => 'copyrightclearance',
605 backend => $self->_backend->name
608 } elsif ( $params->{stage} eq 'copyrightclearance' ) {
609 $params->{stage} = 'init';
612 # First perform API action, then...
617 my $result = $self->_backend->create($args);
619 # ... simple case: we're not at 'commit' stage.
620 my $stage = $result->{stage};
621 return $self->expandTemplate($result)
622 unless ( 'commit' eq $stage );
624 # ... complex case: commit!
626 # Do we still have space for an ILL or should we queue?
627 my $permitted = $self->check_limits(
628 { patron => $self->patron }, { librarycode => $self->branchcode }
631 # Now augment our committed request.
633 $result->{permitted} = $permitted; # Queue request?
637 # ...Updating status!
638 $self->status('QUEUED')->store unless ( $permitted );
640 return $self->expandTemplate($result);
643 =head3 expandTemplate
645 my $params = $abstract->expandTemplate($params);
647 Return a version of $PARAMS augmented with our required template path.
652 my ( $self, $params ) = @_;
653 my $backend = $self->_backend->name;
654 # Generate path to file to load
655 my $backend_dir = $self->_config->backend_dir;
656 my $backend_tmpl = join "/", $backend_dir, $backend;
657 my $intra_tmpl = join "/", $backend_tmpl, "intra-includes",
658 $params->{method} . ".inc";
659 my $opac_tmpl = join "/", $backend_tmpl, "opac-includes",
660 $params->{method} . ".inc";
662 $params->{template} = $intra_tmpl;
663 $params->{opac_template} = $opac_tmpl;
667 #### Abstract Imports
671 my $limit_rules = $abstract->getLimits( {
672 type => 'brw_cat' | 'branch',
676 Return the ILL limit rules for the supplied combination of type / value.
678 As the config may have no rules for this particular type / value combination,
679 or for the default, we must define fall-back values here.
684 my ( $self, $params ) = @_;
685 my $limits = $self->_config->getLimitRules($params->{type});
687 return $limits->{$params->{value}}
688 || $limits->{default}
689 || { count => -1, method => 'active' };
694 my $prefix = $abstract->getPrefix( {
696 branch => $branch_code,
699 Return the ILL prefix as defined by our $params: either per borrower category,
700 per branch or the default.
705 my ( $self, $params ) = @_;
706 my $brn_prefixes = $self->_config->getPrefixes('branch');
707 my $brw_prefixes = $self->_config->getPrefixes('brw_cat');
709 return $brw_prefixes->{$params->{brw_cat}}
710 || $brn_prefixes->{$params->{branch}}
711 || $brw_prefixes->{default}
712 || ""; # "the empty prefix"
715 #### Illrequests Imports
719 my $ok = $illRequests->check_limits( {
720 borrower => $borrower,
721 branchcode => 'branchcode' | undef,
724 Given $PARAMS, a hashref containing a $borrower object and a $branchcode,
725 see whether we are still able to place ILLs.
727 LimitRules are derived from koha-conf.xml:
728 + default limit counts, and counting method
729 + branch specific limit counts & counting method
730 + borrower category specific limit counts & counting method
731 + err on the side of caution: a counting fail will cause fail, even if
732 the other counts passes.
737 my ( $self, $params ) = @_;
738 my $patron = $params->{patron};
739 my $branchcode = $params->{librarycode} || $patron->branchcode;
741 # Establish maximum number of allowed requests
742 my ( $branch_rules, $brw_rules ) = (
749 value => $patron->categorycode,
752 my ( $branch_limit, $brw_limit )
753 = ( $branch_rules->{count}, $brw_rules->{count} );
754 # Establish currently existing requests
755 my ( $branch_count, $brw_count ) = (
756 $self->_limit_counter(
757 $branch_rules->{method}, { branchcode => $branchcode }
759 $self->_limit_counter(
760 $brw_rules->{method}, { borrowernumber => $patron->borrowernumber }
765 # A limit of -1 means no limit exists.
766 # We return blocked if either branch limit or brw limit is reached.
767 if ( ( $branch_limit != -1 && $branch_limit <= $branch_count )
768 || ( $brw_limit != -1 && $brw_limit <= $brw_count ) ) {
776 my ( $self, $method, $target ) = @_;
778 # Establish parameters of counts
780 if ($method && $method eq 'annual') {
781 $resultset = Koha::Illrequests->search({
784 \"YEAR(placed) = YEAR(NOW())"
787 } else { # assume 'active'
788 # XXX: This status list is ugly. There should be a method in config
790 my $where = { status => { -not_in => [ 'QUEUED', 'COMP' ] } };
791 $resultset = Koha::Illrequests->search({ %{$target}, %{$where} });
795 return $resultset->count;
798 =head3 requires_moderation
800 my $status = $illRequest->requires_moderation;
802 Return the name of the status if moderation by staff is required; or 0
807 sub requires_moderation {
809 my $require_moderation = {
810 'CANCREQ' => 'CANCREQ',
812 return $require_moderation->{$self->status};
815 =head3 generic_confirm
817 my $stage_summary = $illRequest->generic_confirm;
819 Handle the generic_confirm extended method. The first stage involves creating
820 a template email for the end user to edit in the browser. The second stage
821 attempts to submit the email.
825 sub generic_confirm {
826 my ( $self, $params ) = @_;
827 my $branch = Koha::Libraries->find($params->{current_branchcode})
828 || die "Invalid current branchcode. Are you logged in as the database user?";
829 if ( !$params->{stage}|| $params->{stage} eq 'init' ) {
830 my $draft->{subject} = "ILL Request";
831 $draft->{body} = <<EOF;
834 We would like to request an interlibrary loan for a title matching the
835 following description:
839 my $details = $self->metadata;
840 while (my ($title, $value) = each %{$details}) {
841 $draft->{body} .= " - " . $title . ": " . $value . "\n"
844 $draft->{body} .= <<EOF;
846 Please let us know if you are able to supply this to us.
852 my @address = map { $branch->$_ }
853 qw/ branchname branchaddress1 branchaddress2 branchaddress3
854 branchzip branchcity branchstate branchcountry branchphone
857 foreach my $line ( @address ) {
858 $address .= $line . "\n" if $line;
861 $draft->{body} .= $address;
863 my $partners = Koha::Patrons->search({
864 categorycode => $self->_config->partner_code
870 method => 'generic_confirm',
874 partners => $partners,
878 } elsif ( 'draft' eq $params->{stage} ) {
879 # Create the to header
880 my $to = $params->{partners};
881 $to =~ s/^\x00//; # Strip leading NULLs
882 $to =~ s/\x00/; /; # Replace others with '; '
883 die "No target email addresses found. Either select at least one partner or check your ILL partner library records." if ( !$to );
884 # Create the from, replyto and sender headers
885 my $from = $branch->branchemail;
886 my $replyto = $branch->branchreplyto || $from;
887 die "Your branch has no email address. Please set it."
890 my $message = Koha::Email->new;
891 my %mail = $message->create_message_headers(
896 subject => Encode::encode( "utf8", $params->{subject} ),
897 message => Encode::encode( "utf8", $params->{body} ),
898 contenttype => 'text/plain',
902 my $result = sendmail(%mail);
904 $self->status("GENREQ")->store;
909 method => 'generic_confirm',
916 status => 'email_failed',
917 message => $Mail::Sendmail::error,
918 method => 'generic_confirm',
923 die "Unknown stage, should not have happened."
929 my $prefix = $record->id_prefix;
931 Return the prefix appropriate for the current Illrequest as derived from the
932 borrower and branch associated with this request's Status, and the config
939 my $brw = $self->patron;
940 my $brw_cat = "dummy";
941 $brw_cat = $brw->categorycode
942 unless ( 'HASH' eq ref($brw) && $brw->{deleted} );
943 my $prefix = $self->getPrefix( {
945 branch => $self->branchcode,
947 $prefix .= "-" if ( $prefix );
953 my $params = $illRequest->_censor($params);
955 Return $params, modified to reflect our censorship requirements.
960 my ( $self, $params ) = @_;
961 my $censorship = $self->_config->censorship;
962 $params->{censor_notes_staff} = $censorship->{censor_notes_staff}
963 if ( $params->{opac} );
964 $params->{display_reply_date} = ( $censorship->{censor_reply_date} ) ? 0 : 1;
971 $json = $illrequest->TO_JSON
973 Overloaded I<TO_JSON> method that takes care of inserting calculated values
974 into the unblessed representation of the object.
979 my ( $self, $embed ) = @_;
981 my $object = $self->SUPER::TO_JSON();
982 $object->{id_prefix} = $self->id_prefix;
984 if ( scalar (keys %$embed) ) {
985 # Augment the request response with patron details if appropriate
986 if ( $embed->{patron} ) {
987 my $patron = $self->patron;
988 $object->{patron} = {
989 firstname => $patron->firstname,
990 surname => $patron->surname,
991 cardnumber => $patron->cardnumber
994 # Augment the request response with metadata details if appropriate
995 if ( $embed->{metadata} ) {
996 $object->{metadata} = $self->metadata;
998 # Augment the request response with status details if appropriate
999 if ( $embed->{capabilities} ) {
1000 $object->{capabilities} = $self->capabilities;
1002 # Augment the request response with library details if appropriate
1003 if ( $embed->{branch} ) {
1004 $object->{branch} = Koha::Libraries->find(
1013 =head2 Internal methods
1020 return 'Illrequest';
1025 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>