Bug 29697: (QA follow-up) Remove useless warning
[koha.git] / t / db_dependent / Illrequests.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use File::Basename qw/basename/;
21
22 use C4::Circulation qw( AddIssue AddReturn );
23
24 use Koha::Database;
25 use Koha::Illrequestattributes;
26 use Koha::Illrequest::Config;
27 use Koha::Biblios;
28 use Koha::Patrons;
29 use Koha::ItemTypes;
30 use Koha::Items;
31 use Koha::Libraries;
32 use Koha::MessageAttributes;
33 use Koha::Notice::Templates;
34 use Koha::AuthorisedValueCategories;
35 use Koha::AuthorisedValues;
36 use t::lib::Mocks;
37 use t::lib::TestBuilder;
38 use Test::MockObject;
39 use Test::MockModule;
40 use Test::Exception;
41 use Test::Deep qw/ cmp_deeply ignore /;
42 use Test::Warn;
43
44 use Test::More tests => 14;
45
46 my $schema = Koha::Database->new->schema;
47 my $builder = t::lib::TestBuilder->new;
48 use_ok('Koha::Illrequest');
49 use_ok('Koha::Illrequests');
50
51 subtest 'Basic object tests' => sub {
52
53     plan tests => 24;
54
55     $schema->storage->txn_begin;
56
57     Koha::Illrequests->search->delete;
58     my $illrq = $builder->build({ source => 'Illrequest' });
59     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
60
61     isa_ok($illrq_obj, 'Koha::Illrequest',
62            "Correctly create and load an illrequest object.");
63     isa_ok($illrq_obj->_config, 'Koha::Illrequest::Config',
64            "Created a config object as part of Illrequest creation.");
65
66     is($illrq_obj->illrequest_id, $illrq->{illrequest_id},
67        "Illrequest_id getter works.");
68     is($illrq_obj->borrowernumber, $illrq->{borrowernumber},
69        "Borrowernumber getter works.");
70     is($illrq_obj->biblio_id, $illrq->{biblio_id},
71        "Biblio_Id getter works.");
72     is($illrq_obj->branchcode, $illrq->{branchcode},
73        "Branchcode getter works.");
74     is($illrq_obj->status, $illrq->{status},
75        "Status getter works.");
76     is($illrq_obj->placed, $illrq->{placed},
77        "Placed getter works.");
78     is($illrq_obj->replied, $illrq->{replied},
79        "Replied getter works.");
80     is($illrq_obj->updated, $illrq->{updated},
81        "Updated getter works.");
82     is($illrq_obj->completed, $illrq->{completed},
83        "Completed getter works.");
84     is($illrq_obj->medium, $illrq->{medium},
85        "Medium getter works.");
86     is($illrq_obj->accessurl, $illrq->{accessurl},
87        "Accessurl getter works.");
88     is($illrq_obj->cost, $illrq->{cost},
89        "Cost getter works.");
90     is($illrq_obj->price_paid, $illrq->{price_paid},
91        "Price_paid getter works.");
92     is($illrq_obj->notesopac, $illrq->{notesopac},
93        "Notesopac getter works.");
94     is($illrq_obj->notesstaff, $illrq->{notesstaff},
95        "Notesstaff getter works.");
96     is($illrq_obj->orderid, $illrq->{orderid},
97        "Orderid getter works.");
98     is($illrq_obj->backend, $illrq->{backend},
99        "Backend getter works.");
100
101     is($illrq_obj->get_type, undef,
102         'get_type() returns undef if no type is set');
103     $builder->build({
104         source => 'Illrequestattribute',
105         value  => {
106             illrequest_id => $illrq_obj->illrequest_id,
107             type => 'type',
108             value => 'book'
109         }
110     });
111     is($illrq_obj->get_type, 'book',
112         'get_type() returns correct type if set');
113
114     isnt($illrq_obj->status, 'COMP',
115          "ILL is not currently marked complete.");
116     $illrq_obj->mark_completed;
117     is($illrq_obj->status, 'COMP',
118        "ILL is now marked complete.");
119
120     $illrq_obj->delete;
121
122     is(Koha::Illrequests->search->count, 0,
123        "No illrequest found after delete.");
124
125     $schema->storage->txn_rollback;
126 };
127
128 subtest 'Working with related objects' => sub {
129
130     plan tests => 7;
131
132     $schema->storage->txn_begin;
133
134     Koha::Illrequests->search->delete;
135
136     my $patron = $builder->build({ source => 'Borrower' });
137     my $illrq = $builder->build({
138         source => 'Illrequest',
139         value => { borrowernumber => $patron->{borrowernumber} }
140     });
141     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
142
143     isa_ok($illrq_obj->patron, 'Koha::Patron',
144            "OK accessing related patron.");
145
146     $builder->build({
147         source => 'Illrequestattribute',
148         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'X' }
149     });
150     $builder->build({
151         source => 'Illrequestattribute',
152         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Y' }
153     });
154     $builder->build({
155         source => 'Illrequestattribute',
156         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Z' }
157     });
158
159     is($illrq_obj->illrequestattributes->count, Koha::Illrequestattributes->search->count,
160        "Fetching expected number of Illrequestattributes for our request.");
161
162     my $illrq1 = $builder->build({ source => 'Illrequest' });
163     $builder->build({
164         source => 'Illrequestattribute',
165         value  => { illrequest_id => $illrq1->{illrequest_id}, type => 'X' }
166     });
167
168     is($illrq_obj->illrequestattributes->count + 1, Koha::Illrequestattributes->search->count,
169        "Fetching expected number of Illrequestattributes for our request.");
170
171     is($illrq_obj->biblio, undef, "->biblio returns undef if no biblio");
172     my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
173     my $req_bib = $builder->build_object({
174         class => 'Koha::Illrequests',
175         value => {
176             biblio_id      => $biblio->biblionumber
177         }
178     });
179     isa_ok($req_bib->biblio, 'Koha::Biblio', "OK accessing related biblio");
180
181     $illrq_obj->delete;
182     is(Koha::Illrequestattributes->search->count, 1,
183        "Correct number of illrequestattributes after delete.");
184
185     isa_ok(Koha::Patrons->find($patron->{borrowernumber}), 'Koha::Patron',
186            "Borrower was not deleted after illrq delete.");
187
188     $schema->storage->txn_rollback;
189 };
190
191 subtest 'Status Graph tests' => sub {
192
193     plan tests => 6;
194
195     $schema->storage->txn_begin;
196
197     my $illrq = $builder->build({source => 'Illrequest'});
198     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
199
200     # _core_status_graph tests: it's just a constant, so here we just make
201     # sure it returns a hashref.
202     is(ref $illrq_obj->_core_status_graph, "HASH",
203        "_core_status_graph returns a hash.");
204
205     # _status_graph_union: let's try different merge operations.
206     # Identity operation
207     is_deeply(
208         $illrq_obj->_status_graph_union($illrq_obj->_core_status_graph, {}),
209         $illrq_obj->_core_status_graph,
210         "core_status_graph + null = core_status_graph"
211     );
212
213     # Simple addition
214     is_deeply(
215         $illrq_obj->_status_graph_union({}, $illrq_obj->_core_status_graph),
216         $illrq_obj->_core_status_graph,
217         "null + core_status_graph = core_status_graph"
218     );
219
220     # Correct merge behaviour
221     is_deeply(
222         $illrq_obj->_status_graph_union({
223             REQ => {
224                 prev_actions   => [ ],
225                 id             => 'REQ',
226                 next_actions   => [ ],
227             },
228         }, {
229             QER => {
230                 prev_actions   => [ 'REQ' ],
231                 id             => 'QER',
232                 next_actions   => [ 'REQ' ],
233             },
234         }),
235         {
236             REQ => {
237                 prev_actions   => [ 'QER' ],
238                 id             => 'REQ',
239                 next_actions   => [ 'QER' ],
240             },
241             QER => {
242                 prev_actions   => [ 'REQ' ],
243                 id             => 'QER',
244                 next_actions   => [ 'REQ' ],
245             },
246         },
247         "REQ atom + linking QER = cyclical status graph"
248     );
249
250     # Create a new node, with no prev_actions and no next_actions. This should
251     # protect us against regressions related to bug 22280.
252     my $new_node = {
253         TEST => {
254             prev_actions   => [ ],
255             id             => 'TEST',
256             next_actions   => [ ],
257         },
258     };
259     # Add the new node to the core_status_grpah
260     my $new_graph = $illrq_obj->_status_graph_union( $new_node, $illrq_obj->_core_status_graph);
261     # Compare the updated graph to the expected graph
262     # The structure we compare against here is just a copy of the structure found
263     # in Koha::Illrequest::_core_status_graph() + the new node we created above
264     cmp_deeply( $new_graph,
265         {
266         TEST => {
267             prev_actions   => [ ],
268             id             => 'TEST',
269             next_actions   => [ ],
270         },
271         NEW => {
272             prev_actions => [ ],                           # Actions containing buttons
273                                                            # leading to this status
274             id             => 'NEW',                       # ID of this status
275             name           => 'New request',               # UI name of this status
276             ui_method_name => 'New request',               # UI name of method leading
277                                                            # to this status
278             method         => 'create',                    # method to this status
279             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all
280                                                            # requests with this status
281             ui_method_icon => 'fa-plus',                   # UI Style class
282         },
283         REQ => {
284             prev_actions   => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
285             id             => 'REQ',
286             name           => 'Requested',
287             ui_method_name => 'Confirm request',
288             method         => 'confirm',
289             next_actions   => [ 'REQREV', 'COMP', 'CHK' ],
290             ui_method_icon => 'fa-check',
291         },
292         GENREQ => {
293             prev_actions   => [ 'NEW', 'REQREV' ],
294             id             => 'GENREQ',
295             name           => 'Requested from partners',
296             ui_method_name => 'Place request with partners',
297             method         => 'generic_confirm',
298             next_actions   => [ 'COMP', 'CHK' ],
299             ui_method_icon => 'fa-send-o',
300         },
301         REQREV => {
302             prev_actions   => [ 'REQ' ],
303             id             => 'REQREV',
304             name           => 'Request reverted',
305             ui_method_name => 'Revert Request',
306             method         => 'cancel',
307             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ],
308             ui_method_icon => 'fa-times',
309         },
310         QUEUED => {
311             prev_actions   => [ ],
312             id             => 'QUEUED',
313             name           => 'Queued request',
314             ui_method_name => 0,
315             method         => 0,
316             next_actions   => [ 'REQ', 'KILL' ],
317             ui_method_icon => 0,
318         },
319         CANCREQ => {
320             prev_actions   => [ 'NEW' ],
321             id             => 'CANCREQ',
322             name           => 'Cancellation requested',
323             ui_method_name => 0,
324             method         => 0,
325             next_actions   => [ 'KILL', 'REQ' ],
326             ui_method_icon => 0,
327         },
328         COMP => {
329             prev_actions   => [ 'REQ' ],
330             id             => 'COMP',
331             name           => 'Completed',
332             ui_method_name => 'Mark completed',
333             method         => 'mark_completed',
334             next_actions   => [ 'CHK' ],
335             ui_method_icon => 'fa-check',
336         },
337         KILL => {
338             prev_actions   => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ],
339             id             => 'KILL',
340             name           => 0,
341             ui_method_name => 'Delete request',
342             method         => 'delete',
343             next_actions   => [ ],
344             ui_method_icon => 'fa-trash',
345         },
346         CHK => {
347             prev_actions   => [ 'REQ', 'GENREQ', 'COMP' ],
348             id             => 'CHK',
349             name           => 'Checked out',
350             ui_method_name => 'Check out',
351             needs_prefs    => [ 'CirculateILL' ],
352             needs_perms    => [ 'user_circulate_circulate_remaining_permissions' ],
353             needs_all      => ignore(),
354             method         => 'check_out',
355             next_actions   => [ ],
356             ui_method_icon => 'fa-upload',
357         },
358         RET => {
359             prev_actions   => [ 'CHK' ],
360             id             => 'RET',
361             name           => 'Returned to library',
362             ui_method_name => 'Check in',
363             method         => 'check_in',
364             next_actions   => [ 'COMP' ],
365             ui_method_icon => 'fa-download',
366         }
367     },
368         "new node + core_status_graph = bigger status graph"
369     ) || diag explain $new_graph;
370
371     # Create a duplicate node
372     my $dupe_node = {
373         REQ => {
374             prev_actions   => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
375             id             => 'REQ',
376             name           => 'Requested',
377             ui_method_name => 'Confirm request dupe',
378             method         => 'confirm',
379             next_actions   => [ 'REQREV', 'COMP', 'CHK' ],
380             ui_method_icon => 'fa-check',
381         }
382     };
383     # Add the dupe node to the core_status_grpah
384     my $dupe_graph = $illrq_obj->_status_graph_union( $illrq_obj->_core_status_graph, $dupe_node);
385     # Compare the updated graph to the expected graph
386     # The structure we compare against here is just a copy of the structure found
387     # in Koha::Illrequest::_core_status_graph() + the new node we created above
388     cmp_deeply( $dupe_graph,
389         {
390         NEW => {
391             prev_actions => [ ],                           # Actions containing buttons
392                                                            # leading to this status
393             id             => 'NEW',                       # ID of this status
394             name           => 'New request',               # UI name of this status
395             ui_method_name => 'New request',               # UI name of method leading
396                                                            # to this status
397             method         => 'create',                    # method to this status
398             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all
399                                                            # requests with this status
400             ui_method_icon => 'fa-plus',                   # UI Style class
401         },
402         REQ => {
403             prev_actions   => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
404             id             => 'REQ',
405             name           => 'Requested',
406             ui_method_name => 'Confirm request dupe',
407             method         => 'confirm',
408             next_actions   => [ 'REQREV', 'COMP', 'CHK' ],
409             ui_method_icon => 'fa-check',
410         },
411         GENREQ => {
412             prev_actions   => [ 'NEW', 'REQREV' ],
413             id             => 'GENREQ',
414             name           => 'Requested from partners',
415             ui_method_name => 'Place request with partners',
416             method         => 'generic_confirm',
417             next_actions   => [ 'COMP', 'CHK' ],
418             ui_method_icon => 'fa-send-o',
419         },
420         REQREV => {
421             prev_actions   => [ 'REQ' ],
422             id             => 'REQREV',
423             name           => 'Request reverted',
424             ui_method_name => 'Revert Request',
425             method         => 'cancel',
426             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ],
427             ui_method_icon => 'fa-times',
428         },
429         QUEUED => {
430             prev_actions   => [ ],
431             id             => 'QUEUED',
432             name           => 'Queued request',
433             ui_method_name => 0,
434             method         => 0,
435             next_actions   => [ 'REQ', 'KILL' ],
436             ui_method_icon => 0,
437         },
438         CANCREQ => {
439             prev_actions   => [ 'NEW' ],
440             id             => 'CANCREQ',
441             name           => 'Cancellation requested',
442             ui_method_name => 0,
443             method         => 0,
444             next_actions   => [ 'KILL', 'REQ' ],
445             ui_method_icon => 0,
446         },
447         COMP => {
448             prev_actions   => [ 'REQ' ],
449             id             => 'COMP',
450             name           => 'Completed',
451             ui_method_name => 'Mark completed',
452             method         => 'mark_completed',
453             next_actions   => [ 'CHK' ],
454             ui_method_icon => 'fa-check',
455         },
456         KILL => {
457             prev_actions   => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ],
458             id             => 'KILL',
459             name           => 0,
460             ui_method_name => 'Delete request',
461             method         => 'delete',
462             next_actions   => [ ],
463             ui_method_icon => 'fa-trash',
464         },
465         CHK => {
466             prev_actions   => [ 'REQ', 'GENREQ', 'COMP' ],
467             id             => 'CHK',
468             name           => 'Checked out',
469             ui_method_name => 'Check out',
470             needs_prefs    => [ 'CirculateILL' ],
471             needs_perms    => [ 'user_circulate_circulate_remaining_permissions' ],
472             needs_all      => ignore(),
473             method         => 'check_out',
474             next_actions   => [ ],
475             ui_method_icon => 'fa-upload',
476         },
477         RET => {
478             prev_actions   => [ 'CHK' ],
479             id             => 'RET',
480             name           => 'Returned to library',
481             ui_method_name => 'Check in',
482             method         => 'check_in',
483             next_actions   => [ 'COMP' ],
484             ui_method_icon => 'fa-download',
485         }
486     },
487         "new node + core_status_graph = bigger status graph"
488     ) || diag explain $dupe_graph;
489
490     $schema->storage->txn_rollback;
491 };
492
493 subtest 'Backend testing (mocks)' => sub {
494
495     plan tests => 13;
496
497     $schema->storage->txn_begin;
498
499     # testing load_backend & available_backends requires that we have at least
500     # the Dummy plugin installed.  load_backend & available_backends don't
501     # currently have tests as a result.
502
503     t::lib::Mocks->mock_config('interlibrary_loans', { backend_dir => 'a_dir' }  );
504     my $backend = Test::MockObject->new;
505     $backend->set_isa('Koha::Illbackends::Mock');
506     $backend->set_always('name', 'Mock');
507
508     my $patron = $builder->build({ source => 'Borrower' });
509     my $illrq = $builder->build_object({
510         class => 'Koha::Illrequests',
511     });
512
513     $illrq->_backend($backend);
514
515     isa_ok($illrq->_backend, 'Koha::Illbackends::Mock',
516            "OK accessing mocked backend.");
517
518     # _backend_capability tests:
519     # We need to test whether this optional feature of a mocked backend
520     # behaves as expected.
521     # 3 scenarios: feature not implemented, feature implemented, but requested
522     # capability is not provided by backend, & feature is implemented &
523     # capability exists.  This method can be used to implement custom backend
524     # functionality, such as unmediated in the BLDSS backend (also see
525     # bugzilla 18837).
526     $backend->set_always('capabilities', undef);
527     is($illrq->_backend_capability('Test'), 0,
528        "0 returned on Mock not implementing capabilities.");
529
530     $backend->set_always('capabilities', 0);
531     is($illrq->_backend_capability('Test'), 0,
532        "0 returned on Mock not implementing Test capability.");
533
534     $backend->set_always('capabilities', sub { return 'bar'; } );
535     is($illrq->_backend_capability('Test'), 'bar',
536        "'bar' returned on Mock implementing Test capability.");
537
538     # metadata test: we need to be sure that we return the arbitrary values
539     # from the backend.
540     $backend->mock(
541         'metadata',
542         sub {
543             my ( $self, $rq ) = @_;
544             return {
545                 ID => $rq->illrequest_id,
546                 Title => $rq->patron->borrowernumber
547             }
548         }
549     );
550
551     is_deeply(
552         $illrq->metadata,
553         {
554             ID => $illrq->illrequest_id,
555             Title => $illrq->patron->borrowernumber
556         },
557         "Test metadata."
558     );
559
560     # capabilities:
561
562     # No backend graph extension
563     $backend->set_always('status_graph', {});
564     is_deeply($illrq->capabilities('COMP'),
565               {
566                   prev_actions   => [ 'REQ' ],
567                   id             => 'COMP',
568                   name           => 'Completed',
569                   ui_method_name => 'Mark completed',
570                   method         => 'mark_completed',
571                   next_actions   => [ 'CHK' ],
572                   ui_method_icon => 'fa-check',
573               },
574               "Dummy status graph for COMP.");
575     is($illrq->capabilities('UNKNOWN'), undef,
576        "Dummy status graph for UNKNOWN.");
577     is_deeply($illrq->capabilities(),
578               $illrq->_core_status_graph,
579               "Dummy full status graph.");
580     # Simple backend graph extension
581     $backend->set_always('status_graph',
582                          {
583                              QER => {
584                                  prev_actions   => [ 'REQ' ],
585                                  id             => 'QER',
586                                  next_actions   => [ 'REQ' ],
587                              },
588                          });
589     is_deeply($illrq->capabilities('QER'),
590               {
591                   prev_actions   => [ 'REQ' ],
592                   id             => 'QER',
593                   next_actions   => [ 'REQ' ],
594               },
595               "Simple status graph for QER.");
596     is($illrq->capabilities('UNKNOWN'), undef,
597        "Simple status graph for UNKNOWN.");
598     is_deeply($illrq->capabilities(),
599               $illrq->_status_graph_union(
600                   $illrq->_core_status_graph,
601                   {
602                       QER => {
603                           prev_actions   => [ 'REQ' ],
604                           id             => 'QER',
605                           next_actions   => [ 'REQ' ],
606                       },
607                   }
608               ),
609               "Simple full status graph.");
610
611     # custom_capability:
612
613     # No backend graph extension
614     $backend->set_always('status_graph', {});
615     is($illrq->custom_capability('unknown', {}), 0,
616        "Unknown candidate.");
617
618     # Simple backend graph extension
619     $backend->set_always('status_graph',
620                          {
621                              ID => {
622                                  prev_actions   => [ 'REQ' ],
623                                  id             => 'ID',
624                                  method         => 'identity',
625                                  next_actions   => [ 'REQ' ],
626                              },
627                          });
628     $backend->mock('identity',
629                    sub { my ( $self, $params ) = @_; return $params->{other}; });
630     is($illrq->custom_capability('identity', { test => 1, method => 'blah' })->{test}, 1,
631        "Resolve identity custom_capability");
632
633     $schema->storage->txn_rollback;
634 };
635
636
637 subtest 'Backend core methods' => sub {
638
639     plan tests => 19;
640
641     $schema->storage->txn_begin;
642
643     # Build infrastructure
644     my $backend = Test::MockObject->new;
645     $backend->set_isa('Koha::Illbackends::Mock');
646     $backend->set_always('name', 'Mock');
647     $backend->mock('capabilities', sub { return 'Mock'; });
648
649     my $config = Test::MockObject->new;
650     $config->set_always('backend_dir', "/tmp");
651     $config->set_always('getLimitRules',
652                         { default => { count => 0, method => 'active' } });
653
654     my $illrq = $builder->build_object({
655         class => 'Koha::Illrequests',
656         value => { backend => undef }
657     });
658     $illrq->_config($config);
659
660     # Test error conditions (no backend)
661     throws_ok { $illrq->load_backend; }
662         'Koha::Exceptions::Ill::InvalidBackendId',
663         'Exception raised correctly';
664
665     throws_ok { $illrq->load_backend(''); }
666         'Koha::Exceptions::Ill::InvalidBackendId',
667         'Exception raised correctly';
668
669     # Now load the mocked backend
670     $illrq->_backend($backend);
671
672     # expandTemplate:
673     is_deeply($illrq->expandTemplate({ test => 1, method => "bar" }),
674               {
675                   test => 1,
676                   method => "bar",
677                   template => "/tmp/Mock/intra-includes/bar.inc",
678                   opac_template => "/tmp/Mock/opac-includes/bar.inc",
679               },
680               "ExpandTemplate");
681
682     # backend_create
683     # we are testing simple cases.
684     $backend->set_series('create',
685                          { stage => 'bar', method => 'create' },
686                          { stage => 'commit', method => 'create' },
687                          { stage => 'commit', method => 'create' },
688                          { stage => 'commit', method => 'create' },
689                          { stage => 'commit', method => 'create' });
690     # Test non-commit
691     is_deeply($illrq->backend_create({test => 1}),
692               {
693                   stage => 'bar', method => 'create',
694                   template => "/tmp/Mock/intra-includes/create.inc",
695                   opac_template => "/tmp/Mock/opac-includes/create.inc",
696               },
697               "Backend create: arbitrary stage.");
698     # Test commit
699     is_deeply($illrq->backend_create({test => 1}),
700               {
701                   stage => 'commit', method => 'create', permitted => 0,
702                   template => "/tmp/Mock/intra-includes/create.inc",
703                   opac_template => "/tmp/Mock/opac-includes/create.inc",
704               },
705               "Backend create: arbitrary stage, not permitted.");
706     is($illrq->status, "QUEUED", "Backend create: queued if restricted.");
707     $config->set_always('getLimitRules', {});
708     $illrq->status('NEW');
709     is_deeply($illrq->backend_create({test => 1}),
710               {
711                   stage => 'commit', method => 'create', permitted => 1,
712                   template => "/tmp/Mock/intra-includes/create.inc",
713                   opac_template => "/tmp/Mock/opac-includes/create.inc",
714               },
715               "Backend create: arbitrary stage, permitted.");
716     is($illrq->status, "NEW", "Backend create: not-queued.");
717
718     # Test that enabling the unmediated workflow causes the backend's
719     # 'unmediated_ill' method to be called
720     t::lib::Mocks::mock_preference('ILLModuleUnmediated', '1');
721     $backend->mock(
722         'capabilities',
723         sub {
724             my ($self, $name) = @_;
725             if ($name eq 'unmediated_ill') {
726                 return sub {
727                     return { unmediated_ill => 1 };
728                 };
729             }
730         }
731     );
732     $illrq->status('NEW');
733     is_deeply(
734         $illrq->backend_create({test => 1}),
735         {
736             'opac_template' => '/tmp/Mock/opac-includes/.inc',
737             'template' => '/tmp/Mock/intra-includes/.inc',
738             'unmediated_ill' => 1
739         },
740         "Backend create: commit stage, permitted, ILLModuleUnmediated enabled."
741     );
742
743     # Test that disabling the unmediated workflow causes the backend's
744     # 'unmediated_ill' method to be NOT called
745     t::lib::Mocks::mock_preference('ILLModuleUnmediated', '0');
746     $illrq->status('NEW');
747     is_deeply(
748         $illrq->backend_create({test => 1}),
749         {
750             stage => 'commit', method => 'create', permitted => 1,
751             template => "/tmp/Mock/intra-includes/create.inc",
752             opac_template => "/tmp/Mock/opac-includes/create.inc",
753         },
754         "Backend create: commit stage, permitted, ILLModuleUnmediated disabled."
755     );
756
757     # backend_renew
758     $backend->set_series('renew', { stage => 'bar', method => 'renew' });
759     is_deeply($illrq->backend_renew({test => 1}),
760               {
761                   stage => 'bar', method => 'renew',
762                   template => "/tmp/Mock/intra-includes/renew.inc",
763                   opac_template => "/tmp/Mock/opac-includes/renew.inc",
764               },
765               "Backend renew: arbitrary stage.");
766
767     # backend_cancel
768     $backend->set_series('cancel', { stage => 'bar', method => 'cancel' });
769     is_deeply($illrq->backend_cancel({test => 1}),
770               {
771                   stage => 'bar', method => 'cancel',
772                   template => "/tmp/Mock/intra-includes/cancel.inc",
773                   opac_template => "/tmp/Mock/opac-includes/cancel.inc",
774               },
775               "Backend cancel: arbitrary stage.");
776
777     # backend_illview
778     $backend->set_series('illview', { stage => '', method => 'illview' });
779     is_deeply($illrq->backend_illview({test => 1}), 0,
780               "Backend illview optional method.");
781
782     # backend_update_status
783     $backend->set_series('update_status', { stage => 'bar', method => 'update_status' });
784     is_deeply($illrq->backend_update_status({test => 1}),
785               {
786                   stage => 'bar', method => 'update_status',
787                   template => "/tmp/Mock/intra-includes/update_status.inc",
788                   opac_template => "/tmp/Mock/opac-includes/update_status.inc",
789               },
790               "Backend update_status: arbitrary stage.");
791
792     # backend_confirm
793     $backend->set_series('confirm', { stage => 'bar', method => 'confirm' });
794     is_deeply($illrq->backend_confirm({test => 1}),
795               {
796                   stage => 'bar', method => 'confirm',
797                   template => "/tmp/Mock/intra-includes/confirm.inc",
798                   opac_template => "/tmp/Mock/opac-includes/confirm.inc",
799               },
800               "Backend confirm: arbitrary stage.");
801
802     $config->set_always('partner_code', "ILLTSTLIB");
803     $backend->set_always('metadata', { Test => "Foobar" });
804     my $illbrn = $builder->build({
805         source => 'Branch',
806         value => { branchemail => "", branchreplyto => "" }
807     });
808     my $partner1 = $builder->build({
809         source => 'Borrower',
810         value => { categorycode => "ILLTSTLIB" },
811     });
812     my $partner2 = $builder->build({
813         source => 'Borrower',
814         value => { categorycode => "ILLTSTLIB" },
815     });
816     my $gen_conf = $illrq->generic_confirm({
817         current_branchcode => $illbrn->{branchcode}
818     });
819     isnt(index($gen_conf->{value}->{draft}->{body}, $backend->metadata->{Test}), -1,
820          "Generic confirm: draft contains metadata."
821     );
822     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner1->{borrowernumber},
823        "Generic cofnirm: partner 1 is correct."
824     );
825     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner2->{borrowernumber},
826        "Generic confirm: partner 2 is correct."
827     );
828
829     dies_ok { $illrq->generic_confirm({
830         current_branchcode => $illbrn->{branchcode},
831         stage => 'draft'
832     }) }
833         "Generic confirm: missing to dies OK.";
834
835     $schema->storage->txn_rollback;
836 };
837
838
839 subtest 'Helpers' => sub {
840
841     plan tests => 21;
842
843     $schema->storage->txn_begin;
844
845     # Build infrastructure
846     my $backend = Test::MockObject->new;
847     $backend->set_isa('Koha::Illbackends::Mock');
848     $backend->set_always('name', 'Mock');
849     $backend->mock(
850         'metadata',
851         sub {
852             my ( $self, $rq ) = @_;
853             return {
854                 title => 'mytitle',
855                 author => 'myauthor'
856             }
857         }
858     );
859
860     my $config = Test::MockObject->new;
861     $config->set_always('backend_dir', "/tmp");
862
863     my $patron = $builder->build({
864         source => 'Borrower',
865         value => { categorycode => "A" }
866     });
867     # Create a mocked branch with no email addressed defined
868     my $illbrn = $builder->build({
869         source => 'Branch',
870         value => {
871             branchcode => 'HDE',
872             branchemail => "",
873             branchillemail => "",
874             branchreplyto => ""
875         }
876     });
877     my $illrq = $builder->build({
878         source => 'Illrequest',
879         value => { branchcode => "HDE", borrowernumber => $patron->{borrowernumber} }
880     });
881     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
882     $illrq_obj->_config($config);
883     $illrq_obj->_backend($backend);
884
885     # getPrefix
886     $config->set_series('getPrefixes',
887                         { HDE => "TEST", TSL => "BAR", default => "DEFAULT" },
888                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
889     is($illrq_obj->getPrefix({ brw_cat => "UNKNOWN", branch => "HDE" }), "TEST",
890        "getPrefix: branch");
891     $config->set_series('getPrefixes',
892                         { HDE => "TEST", TSL => "BAR", default => "DEFAULT" },
893                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
894     is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "",
895        "getPrefix: default");
896     $config->set_always('getPrefixes', {});
897     is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "",
898        "getPrefix: the empty prefix");
899
900     # id_prefix
901     $config->set_series('getPrefixes',
902                         { HDE => "TEST", TSL => "BAR", default => "DEFAULT" },
903                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
904     is($illrq_obj->id_prefix, "TEST-", "id_prefix: branch");
905     $config->set_series('getPrefixes',
906                         { HDET => "TEST", TSLT => "BAR", default => "DEFAULT" },
907                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
908     is($illrq_obj->id_prefix, "", "id_prefix: default");
909
910     # requires_moderation
911     $illrq_obj->status('NEW')->store;
912     is($illrq_obj->requires_moderation, undef, "requires_moderation: No.");
913     $illrq_obj->status('CANCREQ')->store;
914     is($illrq_obj->requires_moderation, 'CANCREQ', "requires_moderation: Yes.");
915
916     #send_patron_notice
917     my $attr = Koha::MessageAttributes->find({ message_name => 'Ill_ready' });
918     C4::Members::Messaging::SetMessagingPreference({
919         borrowernumber => $patron->{borrowernumber},
920         message_attribute_id => $attr->message_attribute_id,
921         message_transport_types => ['email']
922     });
923     my $return_patron = $illrq_obj->send_patron_notice('ILL_PICKUP_READY');
924     my $notice = $schema->resultset('MessageQueue')->search({
925             letter_code => 'ILL_PICKUP_READY',
926             message_transport_type => 'email',
927             borrowernumber => $illrq_obj->borrowernumber
928         })->next()->letter_code;
929     is_deeply(
930         $return_patron,
931         { result => { success => ['email'], fail => [] } },
932         "Correct return when notice created"
933     );
934     is($notice, 'ILL_PICKUP_READY' ,"Notice is correctly created");
935
936     my $return_patron_fail = $illrq_obj->send_patron_notice();
937     is_deeply(
938         $return_patron_fail,
939         { error => 'notice_no_type' },
940         "Correct error when missing type"
941     );
942
943     #send_staff_notice
944     # Specify that no staff notices should be send
945     t::lib::Mocks::mock_preference('ILLSendStaffNotices', '');
946     my $return_staff_cancel_fail =
947         $illrq_obj->send_staff_notice('ILL_REQUEST_CANCEL');
948     is_deeply(
949         $return_staff_cancel_fail,
950         { error => 'notice_not_enabled' },
951         "Does not send notices that are not enabled"
952     );
953     my $queue = $schema->resultset('MessageQueue')->search({
954             letter_code => 'ILL_REQUEST_CANCEL'
955         });
956     is($queue->count, 0, "Notice is not queued");
957
958     # Specify that the cancel notice can be sent
959     t::lib::Mocks::mock_preference('ILLSendStaffNotices', 'ILL_REQUEST_CANCEL');
960     my $return_staff_cancel = $illrq_obj->send_staff_notice(
961         'ILL_REQUEST_CANCEL'
962     );
963     is_deeply(
964         $return_staff_cancel,
965         { success => 'notice_queued' },
966         "Correct return when staff notice created"
967     );
968     $queue = $schema->resultset('MessageQueue')->search({
969             letter_code => 'ILL_REQUEST_CANCEL'
970         });
971     is($queue->count, 1, "Notice queued as expected");
972
973     my $return_staff_fail = $illrq_obj->send_staff_notice();
974     is_deeply(
975         $return_staff_fail,
976         { error => 'notice_no_type' },
977         "Correct error when missing type"
978     );
979     $queue = $schema->resultset('MessageQueue')->search({
980             letter_code => 'ILL_REQUEST_CANCEL'
981         });
982     is($queue->count, 1, "Notice is not queued");
983
984     #get_notice
985     my $not = $illrq_obj->get_notice({
986         notice_code => 'ILL_REQUEST_CANCEL',
987         transport   => 'email'
988     });
989
990     # We test the properties of the hashref separately because the random
991     # hash ordering of the metadata means we can't test the entire thing
992     # with is_deeply
993     ok(
994         $not->{module} eq 'ill',
995         'Correct module return from get_notice'
996     );
997     ok(
998         $not->{name} eq 'ILL request cancelled',
999         'Correct name return from get_notice'
1000     );
1001     ok(
1002         $not->{message_transport_type} eq 'email',
1003         'Correct message_transport_type return from get_notice'
1004     );
1005     ok(
1006         $not->{title} eq 'Interlibrary loan request cancelled',
1007         'Correct title return from get_notice'
1008     );
1009     $not->{content} =~ s/\s//g;
1010
1011     is(
1012         $not->{content},"Thepatronforinterlibraryloansrequest" . $illrq_obj->id . ",withthefollowingdetails,hasrequestedcancellationofthisILLrequest:-author:myauthor-title:mytitle",
1013         'Correct content returned from get_notice with metadata correctly ordered'
1014     );
1015
1016     $schema->storage->txn_rollback;
1017 };
1018
1019
1020 subtest 'Censorship' => sub {
1021
1022     plan tests => 2;
1023
1024     $schema->storage->txn_begin;
1025
1026     # Build infrastructure
1027     my $backend = Test::MockObject->new;
1028     $backend->set_isa('Koha::Illbackends::Mock');
1029     $backend->set_always('name', 'Mock');
1030
1031     my $config = Test::MockObject->new;
1032     $config->set_always('backend_dir', "/tmp");
1033
1034     my $illrq = $builder->build({source => 'Illrequest'});
1035     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
1036     $illrq_obj->_config($config);
1037     $illrq_obj->_backend($backend);
1038
1039     $config->set_always('censorship', { censor_notes_staff => 1, censor_reply_date => 0 });
1040
1041     my $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564 });
1042     is_deeply($censor_out, { foo => 'bar', baz => 564, display_reply_date => 1 },
1043               "_censor: not OPAC, reply_date = 1");
1044
1045     $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564, opac => 1 });
1046     is_deeply($censor_out, {
1047         foo => 'bar', baz => 564, censor_notes_staff => 1,
1048         display_reply_date => 1, opac => 1
1049     }, "_censor: notes_staff = 0, reply_date = 0");
1050
1051     $schema->storage->txn_rollback;
1052 };
1053
1054 subtest 'Checking out' => sub {
1055
1056     plan tests => 17;
1057
1058     $schema->storage->txn_begin;
1059
1060     my $itemtype = $builder->build_object({
1061         class => 'Koha::ItemTypes',
1062         value => {
1063             notforloan => 1
1064         }
1065     });
1066     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1067     my $biblio = $builder->build_sample_biblio();
1068     my $patron = $builder->build_object({
1069         class => 'Koha::Patrons',
1070         value => { category_type => 'x' }
1071     });
1072     my $request = $builder->build_object({
1073         class => 'Koha::Illrequests',
1074         value => {
1075             borrowernumber => $patron->borrowernumber,
1076             biblio_id      => $biblio->biblionumber
1077         }
1078     });
1079
1080     # First test that calling check_out without a stage param returns
1081     # what's required to build the form
1082     my $no_stage = $request->check_out();
1083     is($no_stage->{method}, 'check_out');
1084     is($no_stage->{stage}, 'form');
1085     isa_ok($no_stage->{value}, 'HASH');
1086     isa_ok($no_stage->{value}->{itemtypes}, 'Koha::ItemTypes');
1087     isa_ok($no_stage->{value}->{libraries}, 'Koha::Libraries');
1088     isa_ok($no_stage->{value}->{statistical}, 'Koha::Patrons');
1089     isa_ok($no_stage->{value}->{biblio}, 'Koha::Biblio');
1090
1091     # Now test that form validation works when we supply a 'form' stage
1092     #
1093     # No item_type
1094     my $form_stage_missing_params = $request->check_out({
1095         stage => 'form'
1096     });
1097     is_deeply($form_stage_missing_params->{value}->{errors}, {
1098         item_type => 1
1099     });
1100     # inhouse passed but not a valid patron
1101     my $form_stage_bad_patron = $request->check_out({
1102         stage     => 'form',
1103         item_type => $itemtype->itemtype,
1104         inhouse   => 'I_DONT_EXIST'
1105     });
1106     is_deeply($form_stage_bad_patron->{value}->{errors}, {
1107         inhouse => 1
1108     });
1109     # Too many items attached to biblio
1110     my $item1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
1111     my $item2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
1112     my $form_stage_two_items = $request->check_out({
1113         stage     => 'form',
1114         item_type => $itemtype->itemtype,
1115     });
1116     is_deeply($form_stage_two_items->{value}->{errors}, {
1117         itemcount => 1
1118     });
1119
1120     # Delete the items we created, so we can test that we can create one
1121     $item1->delete;
1122     $item2->delete;
1123
1124     # We need to mock the user environment for AddIssue
1125     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1126     #
1127
1128     # First we pass bad parameters to the item creation to test we're
1129     # catching the failure of item creation
1130     my $form_stage_bad_branchcode;
1131     warning_like {
1132         $form_stage_bad_branchcode = $request->check_out({
1133             stage     => 'form',
1134             item_type => $itemtype->itemtype,
1135             branchcode => '---'
1136         });
1137     } qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/,
1138     "Item creation fails on bad parameters";
1139
1140     is_deeply($form_stage_bad_branchcode->{value}->{errors}, {
1141         item_creation => 1
1142     },"We get expected failure of item creation");
1143
1144     # Now create a proper item
1145     my $form_stage_good_branchcode = $request->check_out({
1146         stage      => 'form',
1147         item_type  => $itemtype->itemtype,
1148         branchcode => $library->branchcode
1149     });
1150     # By default, this item should not be loanable, so check that we're
1151     # informed of that fact
1152     is_deeply(
1153         $form_stage_good_branchcode->{value}->{check_out_errors},
1154         {
1155             error => {
1156                 NOT_FOR_LOAN => 1,
1157                 itemtype_notforloan => $itemtype->itemtype
1158             }
1159         },
1160         "We get expected error on notforloan of item"
1161     );
1162     # Delete the item that was created
1163     $biblio->items->delete;
1164     # Now create an itemtype that is loanable
1165     my $itemtype_loanable = $builder->build_object({
1166         class => 'Koha::ItemTypes',
1167         value => {
1168             notforloan => 0
1169         }
1170     });
1171     # We need to mock the user environment for AddIssue
1172     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1173     my $form_stage_loanable = $request->check_out({
1174         stage      => 'form',
1175         item_type  => $itemtype_loanable->itemtype,
1176         branchcode => $library->branchcode
1177     });
1178     is($form_stage_loanable->{stage}, 'done_check_out');
1179     isa_ok($patron->checkouts, 'Koha::Checkouts');
1180     is($patron->checkouts->count, 1);
1181     is($request->status, 'CHK');
1182
1183     $schema->storage->txn_rollback;
1184 };
1185
1186 subtest 'Checking out with custom due date' => sub {
1187     plan tests => 1;
1188     $schema->storage->txn_begin;
1189
1190     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1191     my $patron = $builder->build_object({
1192         class => 'Koha::Patrons',
1193         value => { category_type => 'x' }
1194     });
1195     my $biblio = $builder->build_sample_biblio();
1196     my $itemtype_loanable = $builder->build_object({
1197         class => 'Koha::ItemTypes',
1198         value => {
1199             notforloan => 0
1200         }
1201     });
1202     my $request = $builder->build_object({
1203         class => 'Koha::Illrequests',
1204         value => {
1205             borrowernumber => $patron->borrowernumber,
1206             biblio_id      => $biblio->biblionumber
1207         }
1208     });
1209
1210     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1211     my $duedate = '2099-05-21 00:00:00';
1212     my $form_stage_loanable = $request->check_out({
1213         stage      => 'form',
1214         item_type  => $itemtype_loanable->itemtype,
1215         branchcode => $library->branchcode,
1216         duedate    => $duedate
1217     });
1218     is($patron->checkouts->next->date_due, $duedate, "Custom due date was used");
1219
1220     $schema->storage->txn_rollback;
1221 };
1222
1223 subtest 'Checking Limits' => sub {
1224
1225     plan tests => 30;
1226
1227     $schema->storage->txn_begin;
1228
1229     # Build infrastructure
1230     my $backend = Test::MockObject->new;
1231     $backend->set_isa('Koha::Illbackends::Mock');
1232     $backend->set_always('name', 'Mock');
1233
1234     my $config = Test::MockObject->new;
1235     $config->set_always('backend_dir', "/tmp");
1236
1237     my $illrq = $builder->build({source => 'Illrequest'});
1238     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
1239     $illrq_obj->_config($config);
1240     $illrq_obj->_backend($backend);
1241
1242     # getLimits
1243     $config->set_series('getLimitRules',
1244                         { CPL => { count => 1, method => 'test' } },
1245                         { default => { count => 0, method => 'active' } });
1246     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
1247               { count => 1, method => 'test' },
1248               "getLimits: by value.");
1249     is_deeply($illrq_obj->getLimits({ type => 'branch' }),
1250               { count => 0, method => 'active' },
1251               "getLimits: by default.");
1252     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
1253               { count => -1, method => 'active' },
1254               "getLimits: by hard-coded.");
1255
1256     #_limit_counter
1257     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1258        1, "_limit_counter: Initial branch annual count.");
1259     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1260        1, "_limit_counter: Initial branch active count.");
1261     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1262        1, "_limit_counter: Initial patron annual count.");
1263     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1264        1, "_limit_counter: Initial patron active count.");
1265     $builder->build({
1266         source => 'Illrequest',
1267         value => {
1268             branchcode => $illrq_obj->branchcode,
1269             borrowernumber => $illrq_obj->borrowernumber,
1270         }
1271     });
1272     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1273        2, "_limit_counter: Add a qualifying request for branch annual count.");
1274     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1275        2, "_limit_counter: Add a qualifying request for branch active count.");
1276     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1277        2, "_limit_counter: Add a qualifying request for patron annual count.");
1278     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1279        2, "_limit_counter: Add a qualifying request for patron active count.");
1280     $builder->build({
1281         source => 'Illrequest',
1282         value => {
1283             branchcode => $illrq_obj->branchcode,
1284             borrowernumber => $illrq_obj->borrowernumber,
1285             placed => "2005-05-31",
1286         }
1287     });
1288     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1289        2, "_limit_counter: Add an out-of-date branch request.");
1290     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1291        3, "_limit_counter: Add a qualifying request for branch active count.");
1292     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1293        2, "_limit_counter: Add an out-of-date patron request.");
1294     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1295        3, "_limit_counter: Add a qualifying request for patron active count.");
1296     $builder->build({
1297         source => 'Illrequest',
1298         value => {
1299             branchcode => $illrq_obj->branchcode,
1300             borrowernumber => $illrq_obj->borrowernumber,
1301             status => "COMP",
1302         }
1303     });
1304     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
1305        3, "_limit_counter: Add a qualifying request for branch annual count.");
1306     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
1307        3, "_limit_counter: Add a completed request for branch active count.");
1308     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
1309        3, "_limit_counter: Add a qualifying request for patron annual count.");
1310     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
1311        3, "_limit_counter: Add a completed request for patron active count.");
1312
1313     # check_limits:
1314
1315     # We've tested _limit_counter, so all we need to test here is whether the
1316     # current counts of 3 for each work as they should against different
1317     # configuration declarations.
1318
1319     # No limits
1320     $config->set_always('getLimitRules', undef);
1321     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1322                                  librarycode => $illrq_obj->branchcode}),
1323        1, "check_limits: no configuration => no limits.");
1324
1325     # Branch tests
1326     $config->set_always('getLimitRules',
1327                         { $illrq_obj->branchcode => { count => 1, method => 'active' } });
1328     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1329                                  librarycode => $illrq_obj->branchcode}),
1330        0, "check_limits: branch active limit exceeded.");
1331     $config->set_always('getLimitRules',
1332                         { $illrq_obj->branchcode => { count => 1, method => 'annual' } });
1333     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1334                                  librarycode => $illrq_obj->branchcode}),
1335        0, "check_limits: branch annual limit exceeded.");
1336     $config->set_always('getLimitRules',
1337                         { $illrq_obj->branchcode => { count => 4, method => 'active' } });
1338     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1339                                  librarycode => $illrq_obj->branchcode}),
1340        1, "check_limits: branch active limit OK.");
1341     $config->set_always('getLimitRules',
1342                         { $illrq_obj->branchcode => { count => 4, method => 'annual' } });
1343     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1344                                  librarycode => $illrq_obj->branchcode}),
1345        1, "check_limits: branch annual limit OK.");
1346
1347     # Patron tests
1348     $config->set_always('getLimitRules',
1349                         { $illrq_obj->patron->categorycode => { count => 1, method => 'active' } });
1350     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1351                                  librarycode => $illrq_obj->branchcode}),
1352        0, "check_limits: patron category active limit exceeded.");
1353     $config->set_always('getLimitRules',
1354                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
1355     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1356                                  librarycode => $illrq_obj->branchcode}),
1357        0, "check_limits: patron category annual limit exceeded.");
1358     $config->set_always('getLimitRules',
1359                         { $illrq_obj->patron->categorycode => { count => 4, method => 'active' } });
1360     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1361                                  librarycode => $illrq_obj->branchcode}),
1362        1, "check_limits: patron category active limit OK.");
1363     $config->set_always('getLimitRules',
1364                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
1365     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1366                                  librarycode => $illrq_obj->branchcode}),
1367        1, "check_limits: patron category annual limit OK.");
1368
1369     # One rule cancels the other
1370     $config->set_series('getLimitRules',
1371                         # Branch rules allow request
1372                         { $illrq_obj->branchcode => { count => 4, method => 'active' } },
1373                         # Patron rule forbids it
1374                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
1375     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1376                                  librarycode => $illrq_obj->branchcode}),
1377        0, "check_limits: patron category veto overrides branch OK.");
1378     $config->set_series('getLimitRules',
1379                         # Branch rules allow request
1380                         { $illrq_obj->branchcode => { count => 1, method => 'active' } },
1381                         # Patron rule forbids it
1382                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
1383     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
1384                                  librarycode => $illrq_obj->branchcode}),
1385        0, "check_limits: branch veto overrides patron category OK.");
1386
1387     $schema->storage->txn_rollback;
1388 };
1389
1390 subtest 'Custom statuses' => sub {
1391
1392     plan tests => 3;
1393
1394     $schema->storage->txn_begin;
1395
1396     my $cat = Koha::AuthorisedValueCategories->search(
1397         {
1398             category_name => 'ILLSTATUS'
1399         }
1400     );
1401
1402     if ($cat->count == 0) {
1403         $cat  = $builder->build_object(
1404             {
1405                 class => 'Koha::AuthorisedValueCategory',
1406                 value => {
1407                     category_name => 'ILLSTATUS'
1408                 }
1409             }
1410         );
1411     };
1412
1413     my $av = $builder->build_object(
1414         {
1415             class => 'Koha::AuthorisedValues',
1416             value => {
1417                 category => 'ILLSTATUS'
1418             }
1419         }
1420     );
1421
1422     is($av->category, 'ILLSTATUS',
1423        "Successfully created authorised value for custom status");
1424
1425     my $ill_req = $builder->build_object(
1426         {
1427             class => 'Koha::Illrequests',
1428             value => {
1429                 status_alias => $av->authorised_value
1430             }
1431         }
1432     );
1433     isa_ok($ill_req->statusalias, 'Koha::AuthorisedValue',
1434            "statusalias correctly returning Koha::AuthorisedValue object");
1435
1436     $ill_req->status("COMP");
1437     is($ill_req->statusalias, undef,
1438         "Koha::Illrequest->status overloading resetting status_alias");
1439
1440     $schema->storage->txn_rollback;
1441 };
1442
1443 subtest 'Checking in hook' => sub {
1444
1445     plan tests => 2;
1446
1447     $schema->storage->txn_begin;
1448
1449     # Build infrastructure
1450     my $backend = Test::MockObject->new;
1451     $backend->set_isa('Koha::Illbackends::Mock');
1452     $backend->set_always('name', 'Mock');
1453
1454     my $config = Test::MockObject->new;
1455     $config->set_always('backend_dir', "/tmp");
1456
1457     my $item   = $builder->build_sample_item();
1458     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1459
1460     t::lib::Mocks::mock_userenv(
1461         {
1462             patron     => $patron,
1463             branchcode => $patron->branchcode
1464         }
1465     );
1466
1467     my $illrq = $builder->build_object(
1468         {
1469             class => 'Koha::Illrequests',
1470             value => {
1471                 biblio_id => $item->biblio->biblionumber,
1472                 status    => 'NEW'
1473             }
1474         }
1475     );
1476
1477     $illrq->_config($config);
1478     $illrq->_backend($backend);
1479
1480     t::lib::Mocks::mock_preference('CirculateILL', 1);
1481
1482     # Add an issue
1483     AddIssue( $patron->unblessed, $item->barcode );
1484     # Make the item withdrawn so checking-in is rejected
1485     t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
1486     $item->set({ withdrawn => 1 })->store;
1487     AddReturn( $item->barcode, $patron->branchcode );
1488     # refresh request
1489     $illrq->discard_changes;
1490     isnt( $illrq->status, 'RET' );
1491
1492     # allow the check-in
1493     $item->set({ withdrawn => 0 })->store;
1494     AddReturn( $item->barcode, $patron->branchcode );
1495     # refresh request
1496     $illrq->discard_changes;
1497     is( $illrq->status, 'RET' );
1498
1499     $schema->storage->txn_rollback;
1500 };