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