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