1 package Koha::Illrequest;
3 # Copyright PTFS Europe 2016,2018
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use Clone qw( clone );
23 use Try::Tiny qw( catch try );
28 use Koha::DateUtils qw( dt_from_string );
29 use Koha::Exceptions::Ill;
30 use Koha::Illcomments;
31 use Koha::Illrequestattributes;
32 use Koha::AuthorisedValue;
33 use Koha::Illrequest::Logger;
35 use Koha::AuthorisedValues;
41 use C4::Circulation qw( CanBookBeIssued AddIssue );
43 use base qw(Koha::Object);
47 Koha::Illrequest - Koha Illrequest Object class
51 An ILLRequest consists of two parts; the Illrequest Koha::Object, and a series
52 of related Illrequestattributes.
54 The former encapsulates the basic necessary information that any ILL requires
55 to be usable in Koha. The latter is a set of additional properties used by
58 The former subsumes the legacy "Status" object. The latter remains
59 encapsulated in the "Record" object.
63 - Anything invoking the ->status method; annotated with:
64 + # Old use of ->status !
68 =head2 Backend API Response Principles
70 All methods should return a hashref in the following format:
76 This should be set to 1 if an error was encountered.
80 The status should be a string from the list of statuses detailed below.
84 The message is a free text field that can be passed on to the end user.
88 The value returned by the method.
92 =head2 Interface Status Messages
96 =item * branch_address_incomplete
98 An interface request has determined branch address details are incomplete.
100 =item * cancel_success
102 The interface's cancel_request method was successful in cancelling the
103 Illrequest using the API.
107 The interface's cancel_request method failed to cancel the Illrequest using
112 The interface's request method returned saying that the desired item is not
113 available for request.
121 my $statusalias = $request->statusalias;
123 Returns a request's status alias, as a Koha::AuthorisedValue instance
124 or implicit undef. This is distinct from status_alias, which only returns
125 the value in the status_alias column, this method returns the entire
126 AuthorisedValue object
132 return unless $self->status_alias;
133 # We can't know which result is the right one if there are multiple
134 # ILLSTATUS authorised values with the same authorised_value column value
135 # so we just use the first
136 return Koha::AuthorisedValues->search(
138 category => 'ILLSTATUS',
139 authorised_value => $self->SUPER::status_alias
146 =head3 illrequestattributes
150 sub illrequestattributes {
152 return Koha::Illrequestattributes->_new_from_dbic(
153 scalar $self->_result->illrequestattributes
163 return Koha::Illcomments->_new_from_dbic(
164 scalar $self->_result->illcomments
174 my $logger = Koha::Illrequest::Logger->new;
175 return $logger->get_request_logs($self);
184 return Koha::Patron->_new_from_dbic(
185 scalar $self->_result->borrowernumber
191 $Illrequest->status_alias(143);
193 Overloaded getter/setter for status_alias,
194 that only returns authorised values from the
195 correct category and records the fact that the status has changed
200 my ($self, $new_status_alias) = @_;
202 my $current_status_alias = $self->SUPER::status_alias;
204 if ($new_status_alias) {
205 # Keep a record of the previous status before we change it,
207 $self->{previous_status} = $current_status_alias ?
208 $current_status_alias :
209 scalar $self->status;
210 # This is hackery to enable us to undefine
211 # status_alias, since we need to have an overloaded
212 # status_alias method to get us around the problem described
214 # https://bugs.koha-community.org/bugzilla3/show_bug.cgi?id=20581#c156
215 # We need a way of accepting implied undef, so we can nullify
216 # the status_alias column, when called from $self->status
217 my $val = $new_status_alias eq "-1" ? undef : $new_status_alias;
218 my $ret = $self->SUPER::status_alias($val);
219 my $val_to_log = $val ? $new_status_alias : scalar $self->status;
221 my $logger = Koha::Illrequest::Logger->new;
222 $logger->log_status_change({
227 delete $self->{previous_status};
231 # We can't know which result is the right one if there are multiple
232 # ILLSTATUS authorised values with the same authorised_value column value
233 # so we just use the first
234 my $alias = Koha::AuthorisedValues->search(
236 category => 'ILLSTATUS',
237 authorised_value => $self->SUPER::status_alias
244 return $alias->authorised_value;
252 $Illrequest->status('CANREQ');
254 Overloaded getter/setter for request status,
255 also nullifies status_alias and records the fact that the status has changed
256 and sends a notice if appropriate
261 my ( $self, $new_status) = @_;
263 my $current_status = $self->SUPER::status;
264 my $current_status_alias = $self->SUPER::status_alias;
267 # Keep a record of the previous status before we change it,
269 $self->{previous_status} = $current_status_alias ?
270 $current_status_alias :
272 my $ret = $self->SUPER::status($new_status)->store;
273 if ($current_status_alias) {
274 # This is hackery to enable us to undefine
275 # status_alias, since we need to have an overloaded
276 # status_alias method to get us around the problem described
278 # https://bugs.koha-community.org/bugzilla3/show_bug.cgi?id=20581#c156
279 # We need a way of passing implied undef to nullify status_alias
280 # so we pass -1, which is special cased in the overloaded setter
281 $self->status_alias("-1");
283 my $logger = Koha::Illrequest::Logger->new;
284 $logger->log_status_change({
289 delete $self->{previous_status};
290 # If status has changed to cancellation requested, send a notice
291 if ($new_status eq 'CANCREQ') {
292 $self->send_staff_notice('ILL_REQUEST_CANCEL');
296 return $current_status;
302 Require "Base.pm" from the relevant ILL backend.
307 my ( $self, $backend_id ) = @_;
309 my @raw = qw/Koha Illbackends/; # Base Path
311 my $backend_name = $backend_id || $self->backend;
313 unless ( defined $backend_name && $backend_name ne '' ) {
314 Koha::Exceptions::Ill::InvalidBackendId->throw(
315 "An invalid backend ID was requested ('')");
318 my $location = join "/", @raw, $backend_name, "Base.pm"; # File to load
319 my $backend_class = join "::", @raw, $backend_name, "Base"; # Package name
321 $self->{_my_backend} = $backend_class->new({
322 config => $self->_config,
323 logger => Koha::Illrequest::Logger->new
331 my $backend = $abstract->_backend($new_backend);
332 my $backend = $abstract->_backend;
334 Getter/Setter for our API object.
339 my ( $self, $backend ) = @_;
340 $self->{_my_backend} = $backend if ( $backend );
341 # Dynamically load our backend object, as late as possible.
342 $self->load_backend unless ( $self->{_my_backend} );
343 return $self->{_my_backend};
346 =head3 _backend_capability
348 my $backend_capability_result = $self->_backend_capability($name, $args);
350 This is a helper method to invoke optional capabilities in the backend. If
351 the capability named by $name is not supported, return 0, else invoke it,
352 passing $args along with the invocation, and return its return value.
354 NOTE: this module suffers from a confusion in termninology:
356 in _backend_capability, the notion of capability refers to an optional feature
357 that is implemented in core, but might not be supported by a given backend.
359 in capabilities & custom_capability, capability refers to entries in the
360 status_graph (after union between backend and core).
362 The easiest way to fix this would be to fix the terminology in
363 capabilities & custom_capability and their callers.
367 sub _backend_capability {
368 my ( $self, $name, $args ) = @_;
370 # See if capability is defined in backend
372 $capability = $self->_backend->capabilities($name);
377 if ( $capability && ref($capability) eq 'CODE' ) {
378 return &{$capability}($args);
386 my $config = $abstract->_config($config);
387 my $config = $abstract->_config;
389 Getter/Setter for our config object.
394 my ( $self, $config ) = @_;
395 $self->{_my_config} = $config if ( $config );
396 # Load our config object, as late as possible.
397 unless ( $self->{_my_config} ) {
398 $self->{_my_config} = Koha::Illrequest::Config->new;
400 return $self->{_my_config};
409 return $self->_backend->metadata($self);
412 =head3 _core_status_graph
414 my $core_status_graph = $illrequest->_core_status_graph;
416 Returns ILL module's default status graph. A status graph defines the list of
417 available actions at any stage in the ILL workflow. This is for instance used
418 by the perl script & template to generate the correct buttons to display to
419 the end user at any given point.
423 sub _core_status_graph {
427 prev_actions => [ ], # Actions containing buttons
428 # leading to this status
429 id => 'NEW', # ID of this status
430 name => 'New request', # UI name of this status
431 ui_method_name => 'New request', # UI name of method leading
433 method => 'create', # method to this status
434 next_actions => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all
435 # requests with this status
436 ui_method_icon => 'fa-plus', # UI Style class
439 prev_actions => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
442 ui_method_name => 'Confirm request',
444 next_actions => [ 'REQREV', 'COMP', 'CHK' ],
445 ui_method_icon => 'fa-check',
448 prev_actions => [ 'NEW', 'REQREV' ],
450 name => 'Requested from partners',
451 ui_method_name => 'Place request with partners',
452 method => 'generic_confirm',
453 next_actions => [ 'COMP', 'CHK' ],
454 ui_method_icon => 'fa-send-o',
457 prev_actions => [ 'REQ' ],
459 name => 'Request reverted',
460 ui_method_name => 'Revert Request',
462 next_actions => [ 'REQ', 'GENREQ', 'KILL' ],
463 ui_method_icon => 'fa-times',
468 name => 'Queued request',
471 next_actions => [ 'REQ', 'KILL' ],
475 prev_actions => [ 'NEW' ],
477 name => 'Cancellation requested',
480 next_actions => [ 'KILL', 'REQ' ],
484 prev_actions => [ 'REQ' ],
487 ui_method_name => 'Mark completed',
488 method => 'mark_completed',
489 next_actions => [ 'CHK' ],
490 ui_method_icon => 'fa-check',
493 prev_actions => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ],
496 ui_method_name => 'Delete request',
499 ui_method_icon => 'fa-trash',
502 prev_actions => [ 'REQ', 'GENREQ', 'COMP' ],
504 name => 'Checked out',
505 ui_method_name => 'Check out',
506 needs_prefs => [ 'CirculateILL' ],
507 needs_perms => [ 'user_circulate_circulate_remaining_permissions' ],
508 # An array of functions that all must return true
509 needs_all => [ sub { my $r = shift; return $r->biblio; } ],
510 method => 'check_out',
512 ui_method_icon => 'fa-upload',
515 prev_actions => [ 'CHK' ],
517 name => 'Returned to library',
518 ui_method_name => 'Check in',
519 method => 'check_in',
520 next_actions => [ 'COMP' ],
521 ui_method_icon => 'fa-download',
526 =head3 _status_graph_union
528 my $status_graph = $illrequest->_status_graph_union($origin, $new_graph);
530 Return a new status_graph, the result of merging $origin & new_graph. This is
531 operation is a union over the sets defied by the two graphs.
533 Each entry in $new_graph is added to $origin. We do not provide a syntax for
534 'subtraction' of entries from $origin.
536 Whilst it is not intended that this works, you can override entries in $origin
537 with entries with the same key in $new_graph. This can lead to problematic
538 behaviour when $new_graph adds an entry, which modifies a dependent entry in
539 $origin, only for the entry in $origin to be replaced later with a new entry
542 NOTE: this procedure does not "re-link" entries in $origin or $new_graph,
543 i.e. each of the graphs need to be correct at the outset of the operation.
547 sub _status_graph_union {
548 my ( $self, $core_status_graph, $backend_status_graph ) = @_;
549 # Create new status graph with:
550 # - all core_status_graph
551 # - for-each each backend_status_graph
552 # + add to new status graph
553 # + for each core prev_action:
554 # * locate core_status
555 # * update next_actions with additional next action.
556 # + for each core next_action:
557 # * locate core_status
558 # * update prev_actions with additional prev action
560 my @core_status_ids = keys %{$core_status_graph};
561 my $status_graph = clone($core_status_graph);
563 foreach my $backend_status_key ( keys %{$backend_status_graph} ) {
564 my $backend_status = $backend_status_graph->{$backend_status_key};
565 # Add to new status graph
566 $status_graph->{$backend_status_key} = $backend_status;
567 # Update all core methods' next_actions.
568 foreach my $prev_action ( @{$backend_status->{prev_actions}} ) {
569 if ( grep { $prev_action eq $_ } @core_status_ids ) {
571 @{$status_graph->{$prev_action}->{next_actions}};
572 push @next_actions, $backend_status_key;
573 $status_graph->{$prev_action}->{next_actions}
577 # Update all core methods' prev_actions
578 foreach my $next_action ( @{$backend_status->{next_actions}} ) {
579 if ( grep { $next_action eq $_ } @core_status_ids ) {
581 @{$status_graph->{$next_action}->{prev_actions}};
582 push @prev_actions, $backend_status_key;
583 $status_graph->{$next_action}->{prev_actions}
589 return $status_graph;
596 my $capabilities = $illrequest->capabilities;
598 Return a hashref mapping methods to operation names supported by the queried
601 Example return value:
603 { create => "Create Request", confirm => "Progress Request" }
605 NOTE: this module suffers from a confusion in termninology:
607 in _backend_capability, the notion of capability refers to an optional feature
608 that is implemented in core, but might not be supported by a given backend.
610 in capabilities & custom_capability, capability refers to entries in the
611 status_graph (after union between backend and core).
613 The easiest way to fix this would be to fix the terminology in
614 capabilities & custom_capability and their callers.
619 my ( $self, $status ) = @_;
620 # Generate up to date status_graph
621 my $status_graph = $self->_status_graph_union(
622 $self->_core_status_graph,
623 $self->_backend->status_graph({
628 # Extract available actions from graph.
629 return $status_graph->{$status} if $status;
630 # Or return entire graph.
631 return $status_graph;
634 =head3 custom_capability
636 Return the result of invoking $CANDIDATE on this request's backend with
637 $PARAMS, or 0 if $CANDIDATE is an unknown method on backend.
639 NOTE: this module suffers from a confusion in termninology:
641 in _backend_capability, the notion of capability refers to an optional feature
642 that is implemented in core, but might not be supported by a given backend.
644 in capabilities & custom_capability, capability refers to entries in the
645 status_graph (after union between backend and core).
647 The easiest way to fix this would be to fix the terminology in
648 capabilities & custom_capability and their callers.
652 sub custom_capability {
653 my ( $self, $candidate, $params ) = @_;
654 foreach my $capability ( values %{$self->capabilities} ) {
655 if ( $candidate eq $capability->{method} ) {
657 $self->_backend->$candidate({
661 return $self->expandTemplate($response);
667 =head3 available_backends
669 Return a list of available backends.
673 sub available_backends {
674 my ( $self, $reduced ) = @_;
675 my $backends = $self->_config->available_backends($reduced);
679 =head3 available_actions
681 Return a list of available actions.
685 sub available_actions {
687 my $current_action = $self->capabilities($self->status);
688 my @available_actions = map { $self->capabilities($_) }
689 @{$current_action->{next_actions}};
690 return \@available_actions;
693 =head3 mark_completed
695 Mark a request as completed (status = COMP).
701 $self->status('COMP')->store;
702 $self->completed(dt_from_string())->store;
707 method => 'mark_completed',
713 =head2 backend_migrate
715 Migrate a request from one backend to another.
719 sub backend_migrate {
720 my ( $self, $params ) = @_;
721 # Set the request's backend to be the destination backend
722 $self->load_backend($params->{backend});
723 my $response = $self->_backend_capability('migrate',{
727 return $self->expandTemplate($response) if $response;
731 =head2 backend_confirm
733 Confirm a request. The backend handles setting of mandatory fields in the commit stage:
739 =item * accessurl, cost (if available).
745 sub backend_confirm {
746 my ( $self, $params ) = @_;
748 my $response = $self->_backend->confirm({
752 return $self->expandTemplate($response);
755 =head3 backend_update_status
759 sub backend_update_status {
760 my ( $self, $params ) = @_;
761 return $self->expandTemplate($self->_backend->update_status($params));
764 =head3 backend_cancel
766 my $ILLResponse = $illRequest->backend_cancel;
768 The standard interface method allowing for request cancellation.
773 my ( $self, $params ) = @_;
775 my $result = $self->_backend->cancel({
780 return $self->expandTemplate($result);
785 my $renew_response = $illRequest->backend_renew;
787 The standard interface method allowing for request renewal queries.
793 return $self->expandTemplate(
794 $self->_backend->renew({
800 =head3 backend_create
802 my $create_response = $abstractILL->backend_create($params);
804 Return an array of Record objects created by querying our backend with
807 In the context of the other ILL methods, this is a special method: we only
808 pass it $params, as it does not yet have any other data associated with it.
813 my ( $self, $params ) = @_;
815 # Establish whether we need to do a generic copyright clearance.
816 if ($params->{opac}) {
817 if ( ( !$params->{stage} || $params->{stage} eq 'init' )
818 && C4::Context->preference("ILLModuleCopyrightClearance") ) {
824 stage => 'copyrightclearance',
827 backend => $self->_backend->name
830 } elsif ( defined $params->{stage}
831 && $params->{stage} eq 'copyrightclearance' ) {
832 $params->{stage} = 'init';
835 # First perform API action, then...
840 my $result = $self->_backend->create($args);
842 # ... simple case: we're not at 'commit' stage.
843 my $stage = $result->{stage};
844 return $self->expandTemplate($result)
845 unless ( 'commit' eq $stage );
847 # ... complex case: commit!
849 # Do we still have space for an ILL or should we queue?
850 my $permitted = $self->check_limits(
851 { patron => $self->patron }, { librarycode => $self->branchcode }
854 # Now augment our committed request.
856 $result->{permitted} = $permitted; # Queue request?
860 # ...Updating status!
861 $self->status('QUEUED')->store unless ( $permitted );
863 ## Handle Unmediated ILLs
865 # For the unmediated workflow we only need to delegate to our backend. If
866 # that backend supports unmediateld_ill, it will do its thing and return a
867 # proper response. If it doesn't then _backend_capability returns 0, so
868 # we keep the current result.
869 if ( C4::Context->preference("ILLModuleUnmediated") && $permitted ) {
870 my $unmediated_result = $self->_backend_capability(
874 $result = $unmediated_result if $unmediated_result;
877 return $self->expandTemplate($result);
880 =head3 expandTemplate
882 my $params = $abstract->expandTemplate($params);
884 Return a version of $PARAMS augmented with our required template path.
889 my ( $self, $params ) = @_;
890 my $backend = $self->_backend->name;
891 # Generate path to file to load
892 my $backend_dir = $self->_config->backend_dir;
893 my $backend_tmpl = join "/", $backend_dir, $backend;
894 my $intra_tmpl = join "/", $backend_tmpl, "intra-includes",
895 ( $params->{method}//q{} ) . ".inc";
896 my $opac_tmpl = join "/", $backend_tmpl, "opac-includes",
897 ( $params->{method}//q{} ) . ".inc";
899 $params->{template} = $intra_tmpl;
900 $params->{opac_template} = $opac_tmpl;
904 #### Abstract Imports
908 my $limit_rules = $abstract->getLimits( {
909 type => 'brw_cat' | 'branch',
913 Return the ILL limit rules for the supplied combination of type / value.
915 As the config may have no rules for this particular type / value combination,
916 or for the default, we must define fall-back values here.
921 my ( $self, $params ) = @_;
922 my $limits = $self->_config->getLimitRules($params->{type});
924 if ( defined $params->{value}
925 && defined $limits->{$params->{value}} ) {
926 return $limits->{$params->{value}};
929 return $limits->{default} || { count => -1, method => 'active' };
935 my $prefix = $abstract->getPrefix( {
936 branch => $branch_code
939 Return the ILL prefix as defined by our $params: either per borrower category,
940 per branch or the default.
945 my ( $self, $params ) = @_;
946 my $brn_prefixes = $self->_config->getPrefixes();
947 return $brn_prefixes->{$params->{branch}} || ""; # "the empty prefix"
952 my $type = $abstract->get_type();
954 Return a string representing the material type of this request or undef
960 my $attr = $self->illrequestattributes->find({ type => 'type'});
965 #### Illrequests Imports
969 my $ok = $illRequests->check_limits( {
970 borrower => $borrower,
971 branchcode => 'branchcode' | undef,
974 Given $PARAMS, a hashref containing a $borrower object and a $branchcode,
975 see whether we are still able to place ILLs.
977 LimitRules are derived from koha-conf.xml:
978 + default limit counts, and counting method
979 + branch specific limit counts & counting method
980 + borrower category specific limit counts & counting method
981 + err on the side of caution: a counting fail will cause fail, even if
982 the other counts passes.
987 my ( $self, $params ) = @_;
988 my $patron = $params->{patron};
989 my $branchcode = $params->{librarycode} || $patron->branchcode;
991 # Establish maximum number of allowed requests
992 my ( $branch_rules, $brw_rules ) = (
999 value => $patron->categorycode,
1002 my ( $branch_limit, $brw_limit )
1003 = ( $branch_rules->{count}, $brw_rules->{count} );
1004 # Establish currently existing requests
1005 my ( $branch_count, $brw_count ) = (
1006 $self->_limit_counter(
1007 $branch_rules->{method}, { branchcode => $branchcode }
1009 $self->_limit_counter(
1010 $brw_rules->{method}, { borrowernumber => $patron->borrowernumber }
1014 # Compare and return
1015 # A limit of -1 means no limit exists.
1016 # We return blocked if either branch limit or brw limit is reached.
1017 if ( ( $branch_limit != -1 && $branch_limit <= $branch_count )
1018 || ( $brw_limit != -1 && $brw_limit <= $brw_count ) ) {
1025 sub _limit_counter {
1026 my ( $self, $method, $target ) = @_;
1028 # Establish parameters of counts
1030 if ($method && $method eq 'annual') {
1031 $resultset = Koha::Illrequests->search({
1034 \"YEAR(placed) = YEAR(NOW())"
1037 } else { # assume 'active'
1038 # XXX: This status list is ugly. There should be a method in config
1040 my $where = { status => { -not_in => [ 'QUEUED', 'COMP' ] } };
1041 $resultset = Koha::Illrequests->search({ %{$target}, %{$where} });
1045 return $resultset->count;
1048 =head3 requires_moderation
1050 my $status = $illRequest->requires_moderation;
1052 Return the name of the status if moderation by staff is required; or 0
1057 sub requires_moderation {
1059 my $require_moderation = {
1060 'CANCREQ' => 'CANCREQ',
1062 return $require_moderation->{$self->status};
1067 my $biblio = $request->biblio;
1069 For a given request, return the biblio associated with it,
1070 or undef if none exists
1077 return if !$self->biblio_id;
1079 return Koha::Biblios->find({
1080 biblionumber => $self->biblio_id
1086 my $stage_summary = $request->check_out;
1088 Handle the check_out method. The first stage involves gathering the required
1089 data from the user via a form, the second stage creates an item and tries to
1090 issue it to the patron. If successful, it notifies the patron, then it
1091 returns a summary of how things went
1096 my ( $self, $params ) = @_;
1098 # Objects required by the template
1099 my $itemtypes = Koha::ItemTypes->search(
1101 { order_by => ['description'] }
1103 my $libraries = Koha::Libraries->search(
1105 { order_by => ['branchcode'] }
1107 my $biblio = $self->biblio;
1109 # Find all statistical patrons
1110 my $statistical_patrons = Koha::Patrons->search(
1111 { 'category_type' => 'x' },
1112 { join => { 'categorycode' => 'borrowers' } }
1115 if (!$params->{stage} || $params->{stage} eq 'init') {
1116 # Present a form to gather the required data
1118 # We may be viewing this page having previously tried to issue
1119 # the item (in which case, we may already have created an item)
1120 # so we pass the biblio for this request
1122 method => 'check_out',
1125 itemtypes => $itemtypes,
1126 libraries => $libraries,
1127 statistical => $statistical_patrons,
1131 } elsif ($params->{stage} eq 'form') {
1132 # Validate what we've got and return with an error if we fail
1134 if (!$params->{item_type} || length $params->{item_type} == 0) {
1135 $errors->{item_type} = 1;
1137 if ($params->{inhouse} && length $params->{inhouse} > 0) {
1138 my $patron_count = Koha::Patrons->search({
1139 cardnumber => $params->{inhouse}
1141 if ($patron_count != 1) {
1142 $errors->{inhouse} = 1;
1146 # Check we don't have more than one item for this bib,
1147 # if we do, something very odd is going on
1148 # Having 1 is OK, it means we're likely trying to issue
1149 # following a previously failed attempt, the item exists
1151 my @items = $biblio->items->as_list;
1152 my $item_count = scalar @items;
1153 if ($item_count > 1) {
1154 $errors->{itemcount} = 1;
1157 # Failed validation, go back to the form
1160 method => 'check_out',
1164 statistical => $statistical_patrons,
1165 itemtypes => $itemtypes,
1166 libraries => $libraries,
1175 # Create an item if one doesn't already exist,
1176 # if one does, use that
1178 if ($item_count == 0) {
1180 biblionumber => $self->biblio_id,
1181 homebranch => $params->{branchcode},
1182 holdingbranch => $params->{branchcode},
1183 location => $params->{branchcode},
1184 itype => $params->{item_type},
1185 barcode => 'ILL-' . $self->illrequest_id
1188 my $item = Koha::Item->new($item_hash)->store;
1189 $itemnumber = $item->itemnumber;
1192 $itemnumber = $items[0]->itemnumber;
1194 # Check we have an item before going forward
1197 method => 'check_out',
1201 itemtypes => $itemtypes,
1202 libraries => $libraries,
1203 statistical => $statistical_patrons,
1204 errors => { item_creation => 1 }
1211 # Gather what we need
1212 my $target_item = Koha::Items->find( $itemnumber );
1213 # Determine who we're issuing to
1214 my $patron = $params->{inhouse} && length $params->{inhouse} > 0 ?
1215 Koha::Patrons->find({ cardnumber => $params->{inhouse} }) :
1220 scalar $target_item->barcode
1222 if ($params->{duedate} && length $params->{duedate} > 0) {
1223 push @issue_args, $params->{duedate};
1225 # Check if we can check out
1226 my ( $error, $confirm, $alerts, $messages ) =
1227 C4::Circulation::CanBookBeIssued(@issue_args);
1229 # If we got anything back saying we can't check out,
1230 # return it to the template
1232 if ( $error && %{$error} ) { $problems->{error} = $error };
1233 if ( $confirm && %{$confirm} ) { $problems->{confirm} = $confirm };
1234 if ( $alerts && %{$alerts} ) { $problems->{alerts} = $alerts };
1235 if ( $messages && %{$messages} ) { $problems->{messages} = $messages };
1239 method => 'check_out',
1243 itemtypes => $itemtypes,
1244 libraries => $libraries,
1245 statistical => $statistical_patrons,
1248 check_out_errors => $problems
1253 # We can allegedly check out, so make it so
1254 # For some reason, AddIssue requires an unblessed Patron
1255 $issue_args[0] = $patron->unblessed;
1256 my $issue = C4::Circulation::AddIssue(@issue_args);
1259 # Update the request status
1260 $self->status('CHK')->store;
1262 method => 'check_out',
1263 stage => 'done_check_out',
1272 method => 'check_out',
1276 itemtypes => $itemtypes,
1277 libraries => $libraries,
1278 errors => { item_check_out => 1 }
1286 =head3 generic_confirm
1288 my $stage_summary = $illRequest->generic_confirm;
1290 Handle the generic_confirm extended method. The first stage involves creating
1291 a template email for the end user to edit in the browser. The second stage
1292 attempts to submit the email.
1296 sub generic_confirm {
1297 my ( $self, $params ) = @_;
1298 my $branch = Koha::Libraries->find($params->{current_branchcode})
1299 || die "Invalid current branchcode. Are you logged in as the database user?";
1300 if ( !$params->{stage}|| $params->{stage} eq 'init' ) {
1301 # Get the message body from the notice definition
1302 my $letter = $self->get_notice({
1303 notice_code => 'ILL_PARTNER_REQ',
1304 transport => 'email'
1307 my $partners = Koha::Patrons->search({
1308 categorycode => $self->_config->partner_code
1314 method => 'generic_confirm',
1318 subject => $letter->{title},
1319 body => $letter->{content}
1321 partners => $partners,
1325 } elsif ( 'draft' eq $params->{stage} ) {
1326 # Create the to header
1327 my $to = $params->{partners};
1328 if ( defined $to ) {
1329 $to =~ s/^\x00//; # Strip leading NULLs
1330 $to =~ s/\x00/; /; # Replace others with '; '
1332 Koha::Exceptions::Ill::NoTargetEmail->throw(
1333 "No target email addresses found. Either select at least one partner or check your ILL partner library records.")
1335 # Create the from, replyto and sender headers
1336 my $from = $branch->from_email_address;
1337 my $replyto = $branch->inbound_ill_address;
1338 Koha::Exceptions::Ill::NoLibraryEmail->throw(
1339 "Your library has no usable email address. Please set it.")
1342 # So we get a notice hashref, then substitute the possibly
1343 # modified title and body from the draft stage
1344 my $letter = $self->get_notice({
1345 notice_code => 'ILL_PARTNER_REQ',
1346 transport => 'email'
1348 $letter->{title} = $params->{subject};
1349 $letter->{content} = $params->{body};
1354 borrowernumber => $self->borrowernumber,
1355 message_transport_type => 'email',
1357 from_address => $from,
1358 reply_address => $replyto
1362 my $result = C4::Letters::EnqueueLetter($params);
1364 $self->status("GENREQ")->store;
1365 $self->_backend_capability(
1366 'set_requested_partners',
1376 method => 'generic_confirm',
1384 status => 'email_failed',
1385 message => 'Email queueing failed',
1386 method => 'generic_confirm',
1390 die "Unknown stage, should not have happened."
1394 =head3 send_patron_notice
1396 my $result = $request->send_patron_notice($notice_code);
1398 Send a specified notice regarding this request to a patron
1402 sub send_patron_notice {
1403 my ( $self, $notice_code ) = @_;
1405 # We need a notice code
1406 if (!$notice_code) {
1408 error => 'notice_no_type'
1412 # Map from the notice code to the messaging preference
1413 my %message_name = (
1414 ILL_PICKUP_READY => 'Ill_ready',
1415 ILL_REQUEST_UNAVAIL => 'Ill_unavailable'
1418 # Get the patron's messaging preferences
1419 my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences({
1420 borrowernumber => $self->borrowernumber,
1421 message_name => $message_name{$notice_code}
1423 my @transports = keys %{ $borrower_preferences->{transports} };
1425 # Notice should come from the library where the request was placed,
1426 # not the patrons home library
1427 my $branch = Koha::Libraries->find($self->branchcode);
1428 my $from_address = $branch->from_email_address;
1429 my $reply_address = $branch->inbound_ill_address;
1431 # Send the notice to the patron via the chosen transport methods
1432 # and record the results
1435 for my $transport (@transports) {
1436 my $letter = $self->get_notice({
1437 notice_code => $notice_code,
1438 transport => $transport
1441 my $result = C4::Letters::EnqueueLetter({
1443 borrowernumber => $self->borrowernumber,
1444 message_transport_type => $transport,
1445 from_address => $from_address,
1446 reply_address => $reply_address
1449 push @success, $transport;
1451 push @fail, $transport;
1454 push @fail, $transport;
1457 if (scalar @success > 0) {
1458 my $logger = Koha::Illrequest::Logger->new;
1459 $logger->log_patron_notice({
1461 notice_code => $notice_code
1466 success => \@success,
1472 =head3 send_staff_notice
1474 my $result = $request->send_staff_notice($notice_code);
1476 Send a specified notice regarding this request to staff
1480 sub send_staff_notice {
1481 my ( $self, $notice_code ) = @_;
1483 # We need a notice code
1484 if (!$notice_code) {
1486 error => 'notice_no_type'
1490 # Get the staff notices that have been assigned for sending in
1492 my $staff_to_send = C4::Context->preference('ILLSendStaffNotices') // q{};
1494 # If it hasn't been enabled in the syspref, we don't want to send it
1495 if ($staff_to_send !~ /\b$notice_code\b/) {
1497 error => 'notice_not_enabled'
1501 my $letter = $self->get_notice({
1502 notice_code => $notice_code,
1503 transport => 'email'
1506 # Try and get an address to which to send staff notices
1507 my $branch = Koha::Libraries->find($self->branchcode);
1508 my $to_address = $branch->inbound_ill_address;
1509 my $from_address = $branch->inbound_ill_address;
1513 borrowernumber => $self->borrowernumber,
1514 message_transport_type => 'email',
1515 from_address => $from_address
1519 $params->{to_address} = $to_address;
1522 error => 'notice_no_create'
1527 C4::Letters::EnqueueLetter($params)
1528 or warn "can't enqueue letter $letter";
1530 success => 'notice_queued'
1534 error => 'notice_no_create'
1541 my $notice = $request->get_notice($params);
1543 Return a compiled notice hashref for the passed notice code
1549 my ( $self, $params ) = @_;
1551 my $title = $self->illrequestattributes->find(
1554 my $author = $self->illrequestattributes->find(
1555 { type => 'author' }
1557 my $metahash = $self->metadata;
1559 foreach my $key (sort { lc $a cmp lc $b } keys %{$metahash}) {
1560 my $value = $metahash->{$key};
1561 push @metaarray, "- $key: $value" if $value;
1563 my $metastring = join("\n", @metaarray);
1564 my $letter = C4::Letters::GetPreparedLetter(
1566 letter_code => $params->{notice_code},
1567 branchcode => $self->branchcode,
1568 message_transport_type => $params->{transport},
1569 lang => $self->patron->lang,
1571 illrequests => $self->illrequest_id,
1572 borrowers => $self->borrowernumber,
1573 biblio => $self->biblio_id,
1574 branches => $self->branchcode,
1577 ill_bib_title => $title ? $title->value : '',
1578 ill_bib_author => $author ? $author->value : '',
1579 ill_full_metadata => $metastring
1588 my $prefix = $record->id_prefix;
1590 Return the prefix appropriate for the current Illrequest as derived from the
1591 borrower and branch associated with this request's Status, and the config
1598 my $prefix = $self->getPrefix( {
1599 branch => $self->branchcode,
1601 $prefix .= "-" if ( $prefix );
1607 my $params = $illRequest->_censor($params);
1609 Return $params, modified to reflect our censorship requirements.
1614 my ( $self, $params ) = @_;
1615 my $censorship = $self->_config->censorship;
1616 $params->{censor_notes_staff} = $censorship->{censor_notes_staff}
1617 if ( $params->{opac} );
1618 $params->{display_reply_date} = ( $censorship->{censor_reply_date} ) ? 0 : 1;
1627 Overloaded I<store> method that, in addition to performing the 'store',
1628 possibly records the fact that something happened
1633 my ( $self, $attrs ) = @_;
1635 my $ret = $self->SUPER::store;
1637 $attrs->{log_origin} = 'core';
1639 if ($ret && defined $attrs) {
1640 my $logger = Koha::Illrequest::Logger->new;
1641 $logger->log_maybe({
1650 =head3 requested_partners
1652 my $partners_string = $illRequest->requested_partners;
1654 Return the string representing the email addresses of the partners to
1655 whom a request has been sent
1659 sub requested_partners {
1661 return $self->_backend_capability(
1662 'get_requested_partners',
1663 { request => $self }
1669 $json = $illrequest->TO_JSON
1671 Overloaded I<TO_JSON> method that takes care of inserting calculated values
1672 into the unblessed representation of the object.
1674 TODO: This method does nothing and is not called anywhere. However, bug 74325
1675 touches it, so keeping this for now until both this and bug 74325 are merged,
1676 at which point we can sort it out and remove it completely
1681 my ( $self, $embed ) = @_;
1683 my $object = $self->SUPER::TO_JSON();
1688 =head2 Internal methods
1695 return 'Illrequest';
1700 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
1701 Andrew Isherwood <andrew.isherwood@ptfs-europe.com>