Bug 18936: Fix IssuingRules/guess_article_requestable_itemtypes.t
[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 use Koha::Database;
22 use Koha::Illrequestattributes;
23 use Koha::Illrequest::Config;
24 use Koha::Patrons;
25 use Koha::AuthorisedValueCategories;
26 use Koha::AuthorisedValues;
27 use t::lib::Mocks;
28 use t::lib::TestBuilder;
29 use Test::MockObject;
30 use Test::MockModule;
31 use Test::Exception;
32
33 use Test::More tests => 11;
34
35 my $schema = Koha::Database->new->schema;
36 my $builder = t::lib::TestBuilder->new;
37 use_ok('Koha::Illrequest');
38 use_ok('Koha::Illrequests');
39
40 subtest 'Basic object tests' => sub {
41
42     plan tests => 24;
43
44     $schema->storage->txn_begin;
45
46     Koha::Illrequests->search->delete;
47     my $illrq = $builder->build({ source => 'Illrequest' });
48     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
49
50     isa_ok($illrq_obj, 'Koha::Illrequest',
51            "Correctly create and load an illrequest object.");
52     isa_ok($illrq_obj->_config, 'Koha::Illrequest::Config',
53            "Created a config object as part of Illrequest creation.");
54
55     is($illrq_obj->illrequest_id, $illrq->{illrequest_id},
56        "Illrequest_id getter works.");
57     is($illrq_obj->borrowernumber, $illrq->{borrowernumber},
58        "Borrowernumber getter works.");
59     is($illrq_obj->biblio_id, $illrq->{biblio_id},
60        "Biblio_Id getter works.");
61     is($illrq_obj->branchcode, $illrq->{branchcode},
62        "Branchcode getter works.");
63     is($illrq_obj->status, $illrq->{status},
64        "Status getter works.");
65     is($illrq_obj->placed, $illrq->{placed},
66        "Placed getter works.");
67     is($illrq_obj->replied, $illrq->{replied},
68        "Replied getter works.");
69     is($illrq_obj->updated, $illrq->{updated},
70        "Updated getter works.");
71     is($illrq_obj->completed, $illrq->{completed},
72        "Completed getter works.");
73     is($illrq_obj->medium, $illrq->{medium},
74        "Medium getter works.");
75     is($illrq_obj->accessurl, $illrq->{accessurl},
76        "Accessurl getter works.");
77     is($illrq_obj->cost, $illrq->{cost},
78        "Cost getter works.");
79     is($illrq_obj->price_paid, $illrq->{price_paid},
80        "Price_paid getter works.");
81     is($illrq_obj->notesopac, $illrq->{notesopac},
82        "Notesopac getter works.");
83     is($illrq_obj->notesstaff, $illrq->{notesstaff},
84        "Notesstaff getter works.");
85     is($illrq_obj->orderid, $illrq->{orderid},
86        "Orderid getter works.");
87     is($illrq_obj->backend, $illrq->{backend},
88        "Backend getter works.");
89
90     is($illrq_obj->get_type, undef,
91         'get_type() returns undef if no type is set');
92     $builder->build({
93         source => 'Illrequestattribute',
94         value  => {
95             illrequest_id => $illrq_obj->illrequest_id,
96             type => 'type',
97             value => 'book'
98         }
99     });
100     is($illrq_obj->get_type, 'book',
101         'get_type() returns correct type if set');
102
103     isnt($illrq_obj->status, 'COMP',
104          "ILL is not currently marked complete.");
105     $illrq_obj->mark_completed;
106     is($illrq_obj->status, 'COMP',
107        "ILL is now marked complete.");
108
109     $illrq_obj->delete;
110
111     is(Koha::Illrequests->search->count, 0,
112        "No illrequest found after delete.");
113
114     $schema->storage->txn_rollback;
115 };
116
117 subtest 'Working with related objects' => sub {
118
119     plan tests => 5;
120
121     $schema->storage->txn_begin;
122
123     Koha::Illrequests->search->delete;
124
125     my $patron = $builder->build({ source => 'Borrower' });
126     my $illrq = $builder->build({
127         source => 'Illrequest',
128         value => { borrowernumber => $patron->{borrowernumber} }
129     });
130     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
131
132     isa_ok($illrq_obj->patron, 'Koha::Patron',
133            "OK accessing related patron.");
134
135     $builder->build({
136         source => 'Illrequestattribute',
137         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'X' }
138     });
139     $builder->build({
140         source => 'Illrequestattribute',
141         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Y' }
142     });
143     $builder->build({
144         source => 'Illrequestattribute',
145         value  => { illrequest_id => $illrq_obj->illrequest_id, type => 'Z' }
146     });
147
148     is($illrq_obj->illrequestattributes->count, Koha::Illrequestattributes->search->count,
149        "Fetching expected number of Illrequestattributes for our request.");
150
151     my $illrq1 = $builder->build({ source => 'Illrequest' });
152     $builder->build({
153         source => 'Illrequestattribute',
154         value  => { illrequest_id => $illrq1->{illrequest_id}, type => 'X' }
155     });
156
157     is($illrq_obj->illrequestattributes->count + 1, Koha::Illrequestattributes->search->count,
158        "Fetching expected number of Illrequestattributes for our request.");
159
160     $illrq_obj->delete;
161     is(Koha::Illrequestattributes->search->count, 1,
162        "Correct number of illrequestattributes after delete.");
163
164     isa_ok(Koha::Patrons->find($patron->{borrowernumber}), 'Koha::Patron',
165            "Borrower was not deleted after illrq delete.");
166
167     $schema->storage->txn_rollback;
168 };
169
170 subtest 'Status Graph tests' => sub {
171
172     plan tests => 5;
173
174     $schema->storage->txn_begin;
175
176     my $illrq = $builder->build({source => 'Illrequest'});
177     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
178
179     # _core_status_graph tests: it's just a constant, so here we just make
180     # sure it returns a hashref.
181     is(ref $illrq_obj->_core_status_graph, "HASH",
182        "_core_status_graph returns a hash.");
183
184     # _status_graph_union: let's try different merge operations.
185     # Identity operation
186     is_deeply(
187         $illrq_obj->_status_graph_union($illrq_obj->_core_status_graph, {}),
188         $illrq_obj->_core_status_graph,
189         "core_status_graph + null = core_status_graph"
190     );
191
192     # Simple addition
193     is_deeply(
194         $illrq_obj->_status_graph_union({}, $illrq_obj->_core_status_graph),
195         $illrq_obj->_core_status_graph,
196         "null + core_status_graph = core_status_graph"
197     );
198
199     # Correct merge behaviour
200     is_deeply(
201         $illrq_obj->_status_graph_union({
202             REQ => {
203                 prev_actions   => [ ],
204                 id             => 'REQ',
205                 next_actions   => [ ],
206             },
207         }, {
208             QER => {
209                 prev_actions   => [ 'REQ' ],
210                 id             => 'QER',
211                 next_actions   => [ 'REQ' ],
212             },
213         }),
214         {
215             REQ => {
216                 prev_actions   => [ 'QER' ],
217                 id             => 'REQ',
218                 next_actions   => [ 'QER' ],
219             },
220             QER => {
221                 prev_actions   => [ 'REQ' ],
222                 id             => 'QER',
223                 next_actions   => [ 'REQ' ],
224             },
225         },
226         "REQ atom + linking QER = cyclical status graph"
227     );
228
229     # Create a new node, with no prev_actions and no next_actions. This should
230     # protect us against regressions related to bug 22280.
231     my $new_node = {
232         TEST => {
233             prev_actions   => [ ],
234             id             => 'TEST',
235             next_actions   => [ ],
236         },
237     };
238     # Add the new node to the core_status_grpah
239     my $new_graph = $illrq_obj->_status_graph_union( $new_node, $illrq_obj->_core_status_graph);
240     # Compare the updated graph to the expected graph
241     # The structure we compare against here is just a copy of the structure found
242     # in Koha::Illrequest::_core_status_graph() + the new node we created above
243     is_deeply( $new_graph,
244         {
245         NEW => {
246             prev_actions => [ ],                           # Actions containing buttons
247                                                            # leading to this status
248             id             => 'NEW',                       # ID of this status
249             name           => 'New request',               # UI name of this status
250             ui_method_name => 'New request',               # UI name of method leading
251                                                            # to this status
252             method         => 'create',                    # method to this status
253             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all
254                                                            # requests with this status
255             ui_method_icon => 'fa-plus',                   # UI Style class
256         },
257         REQ => {
258             prev_actions   => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ],
259             id             => 'REQ',
260             name           => 'Requested',
261             ui_method_name => 'Confirm request',
262             method         => 'confirm',
263             next_actions   => [ 'REQREV', 'COMP' ],
264             ui_method_icon => 'fa-check',
265         },
266         GENREQ => {
267             prev_actions   => [ 'NEW', 'REQREV' ],
268             id             => 'GENREQ',
269             name           => 'Requested from partners',
270             ui_method_name => 'Place request with partners',
271             method         => 'generic_confirm',
272             next_actions   => [ 'COMP' ],
273             ui_method_icon => 'fa-send-o',
274         },
275         REQREV => {
276             prev_actions   => [ 'REQ' ],
277             id             => 'REQREV',
278             name           => 'Request reverted',
279             ui_method_name => 'Revert Request',
280             method         => 'cancel',
281             next_actions   => [ 'REQ', 'GENREQ', 'KILL' ],
282             ui_method_icon => 'fa-times',
283         },
284         TEST => {
285             prev_actions   => [ ],
286             id             => 'TEST',
287             next_actions   => [ ],
288         },
289         QUEUED => {
290             prev_actions   => [ ],
291             id             => 'QUEUED',
292             name           => 'Queued request',
293             ui_method_name => 0,
294             method         => 0,
295             next_actions   => [ 'REQ', 'KILL' ],
296             ui_method_icon => 0,
297         },
298         CANCREQ => {
299             prev_actions   => [ 'NEW' ],
300             id             => 'CANCREQ',
301             name           => 'Cancellation requested',
302             ui_method_name => 0,
303             method         => 0,
304             next_actions   => [ 'KILL', 'REQ' ],
305             ui_method_icon => 0,
306         },
307         COMP => {
308             prev_actions   => [ 'REQ' ],
309             id             => 'COMP',
310             name           => 'Completed',
311             ui_method_name => 'Mark completed',
312             method         => 'mark_completed',
313             next_actions   => [ ],
314             ui_method_icon => 'fa-check',
315         },
316         KILL => {
317             prev_actions   => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ],
318             id             => 'KILL',
319             name           => 0,
320             ui_method_name => 'Delete request',
321             method         => 'delete',
322             next_actions   => [ ],
323             ui_method_icon => 'fa-trash',
324         },
325     },
326         "new node + core_status_graph = bigger status graph"
327     ) || diag explain $new_graph;
328
329     $schema->storage->txn_rollback;
330 };
331
332 subtest 'Backend testing (mocks)' => sub {
333
334     plan tests => 13;
335
336     $schema->storage->txn_begin;
337
338     # testing load_backend & available_backends requires that we have at least
339     # the Dummy plugin installed.  load_backend & available_backends don't
340     # currently have tests as a result.
341
342     t::lib::Mocks->mock_config('interlibrary_loans', { backend_dir => 'a_dir' }  );
343     my $backend = Test::MockObject->new;
344     $backend->set_isa('Koha::Illbackends::Mock');
345     $backend->set_always('name', 'Mock');
346
347     my $patron = $builder->build({ source => 'Borrower' });
348     my $illrq = $builder->build_object({
349         class => 'Koha::Illrequests',
350         value => { borrowernumber => $patron->{borrowernumber} }
351     });
352
353     $illrq->_backend($backend);
354
355     isa_ok($illrq->_backend, 'Koha::Illbackends::Mock',
356            "OK accessing mocked backend.");
357
358     # _backend_capability tests:
359     # We need to test whether this optional feature of a mocked backend
360     # behaves as expected.
361     # 3 scenarios: feature not implemented, feature implemented, but requested
362     # capability is not provided by backend, & feature is implemented &
363     # capability exists.  This method can be used to implement custom backend
364     # functionality, such as unmediated in the BLDSS backend (also see
365     # bugzilla 18837).
366     $backend->set_always('capabilities', undef);
367     is($illrq->_backend_capability('Test'), 0,
368        "0 returned on Mock not implementing capabilities.");
369
370     $backend->set_always('capabilities', 0);
371     is($illrq->_backend_capability('Test'), 0,
372        "0 returned on Mock not implementing Test capability.");
373
374     $backend->set_always('capabilities', sub { return 'bar'; } );
375     is($illrq->_backend_capability('Test'), 'bar',
376        "'bar' returned on Mock implementing Test capability.");
377
378     # metadata test: we need to be sure that we return the arbitrary values
379     # from the backend.
380     $backend->mock(
381         'metadata',
382         sub {
383             my ( $self, $rq ) = @_;
384             return {
385                 ID => $rq->illrequest_id,
386                 Title => $rq->patron->borrowernumber
387             }
388         }
389     );
390
391     is_deeply(
392         $illrq->metadata,
393         {
394             ID => $illrq->illrequest_id,
395             Title => $illrq->patron->borrowernumber
396         },
397         "Test metadata."
398     );
399
400     # capabilities:
401
402     # No backend graph extension
403     $backend->set_always('status_graph', {});
404     is_deeply($illrq->capabilities('COMP'),
405               {
406                   prev_actions   => [ 'REQ' ],
407                   id             => 'COMP',
408                   name           => 'Completed',
409                   ui_method_name => 'Mark completed',
410                   method         => 'mark_completed',
411                   next_actions   => [ ],
412                   ui_method_icon => 'fa-check',
413               },
414               "Dummy status graph for COMP.");
415     is($illrq->capabilities('UNKNOWN'), undef,
416        "Dummy status graph for UNKNOWN.");
417     is_deeply($illrq->capabilities(),
418               $illrq->_core_status_graph,
419               "Dummy full status graph.");
420     # Simple backend graph extension
421     $backend->set_always('status_graph',
422                          {
423                              QER => {
424                                  prev_actions   => [ 'REQ' ],
425                                  id             => 'QER',
426                                  next_actions   => [ 'REQ' ],
427                              },
428                          });
429     is_deeply($illrq->capabilities('QER'),
430               {
431                   prev_actions   => [ 'REQ' ],
432                   id             => 'QER',
433                   next_actions   => [ 'REQ' ],
434               },
435               "Simple status graph for QER.");
436     is($illrq->capabilities('UNKNOWN'), undef,
437        "Simple status graph for UNKNOWN.");
438     is_deeply($illrq->capabilities(),
439               $illrq->_status_graph_union(
440                   $illrq->_core_status_graph,
441                   {
442                       QER => {
443                           prev_actions   => [ 'REQ' ],
444                           id             => 'QER',
445                           next_actions   => [ 'REQ' ],
446                       },
447                   }
448               ),
449               "Simple full status graph.");
450
451     # custom_capability:
452
453     # No backend graph extension
454     $backend->set_always('status_graph', {});
455     is($illrq->custom_capability('unknown', {}), 0,
456        "Unknown candidate.");
457
458     # Simple backend graph extension
459     $backend->set_always('status_graph',
460                          {
461                              ID => {
462                                  prev_actions   => [ 'REQ' ],
463                                  id             => 'ID',
464                                  method         => 'identity',
465                                  next_actions   => [ 'REQ' ],
466                              },
467                          });
468     $backend->mock('identity',
469                    sub { my ( $self, $params ) = @_; return $params->{other}; });
470     is($illrq->custom_capability('identity', { test => 1, method => 'blah' })->{test}, 1,
471        "Resolve identity custom_capability");
472
473     $schema->storage->txn_rollback;
474 };
475
476
477 subtest 'Backend core methods' => sub {
478
479     plan tests => 19;
480
481     $schema->storage->txn_begin;
482
483     # Build infrastructure
484     my $backend = Test::MockObject->new;
485     $backend->set_isa('Koha::Illbackends::Mock');
486     $backend->set_always('name', 'Mock');
487     $backend->mock('capabilities', sub { return 'Mock'; });
488
489     my $config = Test::MockObject->new;
490     $config->set_always('backend_dir', "/tmp");
491     $config->set_always('getLimitRules',
492                         { default => { count => 0, method => 'active' } });
493
494     my $illrq = $builder->build_object({
495         class => 'Koha::Illrequests',
496         value => { backend => undef }
497     });
498     $illrq->_config($config);
499
500     # Test error conditions (no backend)
501     throws_ok { $illrq->load_backend; }
502         'Koha::Exceptions::Ill::InvalidBackendId',
503         'Exception raised correctly';
504
505     throws_ok { $illrq->load_backend(''); }
506         'Koha::Exceptions::Ill::InvalidBackendId',
507         'Exception raised correctly';
508
509     # Now load the mocked backend
510     $illrq->_backend($backend);
511
512     # expandTemplate:
513     is_deeply($illrq->expandTemplate({ test => 1, method => "bar" }),
514               {
515                   test => 1,
516                   method => "bar",
517                   template => "/tmp/Mock/intra-includes/bar.inc",
518                   opac_template => "/tmp/Mock/opac-includes/bar.inc",
519               },
520               "ExpandTemplate");
521
522     # backend_create
523     # we are testing simple cases.
524     $backend->set_series('create',
525                          { stage => 'bar', method => 'create' },
526                          { stage => 'commit', method => 'create' },
527                          { stage => 'commit', method => 'create' },
528                          { stage => 'commit', method => 'create' },
529                          { stage => 'commit', method => 'create' });
530     # Test non-commit
531     is_deeply($illrq->backend_create({test => 1}),
532               {
533                   stage => 'bar', method => 'create',
534                   template => "/tmp/Mock/intra-includes/create.inc",
535                   opac_template => "/tmp/Mock/opac-includes/create.inc",
536               },
537               "Backend create: arbitrary stage.");
538     # Test commit
539     is_deeply($illrq->backend_create({test => 1}),
540               {
541                   stage => 'commit', method => 'create', permitted => 0,
542                   template => "/tmp/Mock/intra-includes/create.inc",
543                   opac_template => "/tmp/Mock/opac-includes/create.inc",
544               },
545               "Backend create: arbitrary stage, not permitted.");
546     is($illrq->status, "QUEUED", "Backend create: queued if restricted.");
547     $config->set_always('getLimitRules', {});
548     $illrq->status('NEW');
549     is_deeply($illrq->backend_create({test => 1}),
550               {
551                   stage => 'commit', method => 'create', permitted => 1,
552                   template => "/tmp/Mock/intra-includes/create.inc",
553                   opac_template => "/tmp/Mock/opac-includes/create.inc",
554               },
555               "Backend create: arbitrary stage, permitted.");
556     is($illrq->status, "NEW", "Backend create: not-queued.");
557
558     # Test that enabling the unmediated workflow causes the backend's
559     # 'unmediated_ill' method to be called
560     t::lib::Mocks::mock_preference('ILLModuleUnmediated', '1');
561     $backend->mock(
562         'capabilities',
563         sub {
564             my ($self, $name) = @_;
565             if ($name eq 'unmediated_ill') {
566                 return sub {
567                     return { unmediated_ill => 1 };
568                 };
569             }
570         }
571     );
572     $illrq->status('NEW');
573     is_deeply(
574         $illrq->backend_create({test => 1}),
575         {
576             'opac_template' => '/tmp/Mock/opac-includes/.inc',
577             'template' => '/tmp/Mock/intra-includes/.inc',
578             'unmediated_ill' => 1
579         },
580         "Backend create: commit stage, permitted, ILLModuleUnmediated enabled."
581     );
582
583     # Test that disabling the unmediated workflow causes the backend's
584     # 'unmediated_ill' method to be NOT called
585     t::lib::Mocks::mock_preference('ILLModuleUnmediated', '0');
586     $illrq->status('NEW');
587     is_deeply(
588         $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: commit stage, permitted, ILLModuleUnmediated disabled."
595     );
596
597     # backend_renew
598     $backend->set_series('renew', { stage => 'bar', method => 'renew' });
599     is_deeply($illrq->backend_renew({test => 1}),
600               {
601                   stage => 'bar', method => 'renew',
602                   template => "/tmp/Mock/intra-includes/renew.inc",
603                   opac_template => "/tmp/Mock/opac-includes/renew.inc",
604               },
605               "Backend renew: arbitrary stage.");
606
607     # backend_cancel
608     $backend->set_series('cancel', { stage => 'bar', method => 'cancel' });
609     is_deeply($illrq->backend_cancel({test => 1}),
610               {
611                   stage => 'bar', method => 'cancel',
612                   template => "/tmp/Mock/intra-includes/cancel.inc",
613                   opac_template => "/tmp/Mock/opac-includes/cancel.inc",
614               },
615               "Backend cancel: arbitrary stage.");
616
617     # backend_update_status
618     $backend->set_series('update_status', { stage => 'bar', method => 'update_status' });
619     is_deeply($illrq->backend_update_status({test => 1}),
620               {
621                   stage => 'bar', method => 'update_status',
622                   template => "/tmp/Mock/intra-includes/update_status.inc",
623                   opac_template => "/tmp/Mock/opac-includes/update_status.inc",
624               },
625               "Backend update_status: arbitrary stage.");
626
627     # backend_confirm
628     $backend->set_series('confirm', { stage => 'bar', method => 'confirm' });
629     is_deeply($illrq->backend_confirm({test => 1}),
630               {
631                   stage => 'bar', method => 'confirm',
632                   template => "/tmp/Mock/intra-includes/confirm.inc",
633                   opac_template => "/tmp/Mock/opac-includes/confirm.inc",
634               },
635               "Backend confirm: arbitrary stage.");
636
637     $config->set_always('partner_code', "ILLTSTLIB");
638     $backend->set_always('metadata', { Test => "Foobar" });
639     my $illbrn = $builder->build({
640         source => 'Branch',
641         value => { branchemail => "", branchreplyto => "" }
642     });
643     my $partner1 = $builder->build({
644         source => 'Borrower',
645         value => { categorycode => "ILLTSTLIB" },
646     });
647     my $partner2 = $builder->build({
648         source => 'Borrower',
649         value => { categorycode => "ILLTSTLIB" },
650     });
651     my $gen_conf = $illrq->generic_confirm({
652         current_branchcode => $illbrn->{branchcode}
653     });
654     isnt(index($gen_conf->{value}->{draft}->{body}, $backend->metadata->{Test}), -1,
655          "Generic confirm: draft contains metadata."
656     );
657     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner1->{borrowernumber},
658        "Generic cofnirm: partner 1 is correct."
659     );
660     is($gen_conf->{value}->{partners}->next->borrowernumber, $partner2->{borrowernumber},
661        "Generic confirm: partner 2 is correct."
662     );
663
664     dies_ok { $illrq->generic_confirm({
665         current_branchcode => $illbrn->{branchcode},
666         stage => 'draft'
667     }) }
668         "Generic confirm: missing to dies OK.";
669
670     dies_ok { $illrq->generic_confirm({
671         current_branchcode => $illbrn->{branchcode},
672         partners => $partner1->{email},
673         stage => 'draft'
674     }) }
675         "Generic confirm: missing from dies OK.";
676
677     $schema->storage->txn_rollback;
678 };
679
680
681 subtest 'Helpers' => sub {
682
683     plan tests => 7;
684
685     $schema->storage->txn_begin;
686
687     # Build infrastructure
688     my $backend = Test::MockObject->new;
689     $backend->set_isa('Koha::Illbackends::Mock');
690     $backend->set_always('name', 'Mock');
691
692     my $config = Test::MockObject->new;
693     $config->set_always('backend_dir', "/tmp");
694
695     my $patron = $builder->build({
696         source => 'Borrower',
697         value => { categorycode => "A" }
698     });
699     my $illrq = $builder->build({
700         source => 'Illrequest',
701         value => { branchcode => "CPL", borrowernumber => $patron->{borrowernumber} }
702     });
703     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
704     $illrq_obj->_config($config);
705     $illrq_obj->_backend($backend);
706
707     # getPrefix
708     $config->set_series('getPrefixes',
709                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
710                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
711     is($illrq_obj->getPrefix({ brw_cat => "UNKNOWN", branch => "CPL" }), "TEST",
712        "getPrefix: branch");
713     $config->set_series('getPrefixes',
714                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
715                         { A => "ATEST", C => "CBAR", default => "DEFAULT" });
716     is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "",
717        "getPrefix: default");
718     $config->set_always('getPrefixes', {});
719     is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "",
720        "getPrefix: the empty prefix");
721
722     # id_prefix
723     $config->set_series('getPrefixes',
724                         { CPL => "TEST", TSL => "BAR", default => "DEFAULT" },
725                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
726     is($illrq_obj->id_prefix, "TEST-", "id_prefix: branch");
727     $config->set_series('getPrefixes',
728                         { CPLT => "TEST", TSLT => "BAR", default => "DEFAULT" },
729                         { AB => "ATEST", CD => "CBAR", default => "DEFAULT" });
730     is($illrq_obj->id_prefix, "", "id_prefix: default");
731
732     # requires_moderation
733     $illrq_obj->status('NEW')->store;
734     is($illrq_obj->requires_moderation, undef, "requires_moderation: No.");
735     $illrq_obj->status('CANCREQ')->store;
736     is($illrq_obj->requires_moderation, 'CANCREQ', "requires_moderation: Yes.");
737
738     $schema->storage->txn_rollback;
739 };
740
741
742 subtest 'Censorship' => sub {
743
744     plan tests => 2;
745
746     $schema->storage->txn_begin;
747
748     # Build infrastructure
749     my $backend = Test::MockObject->new;
750     $backend->set_isa('Koha::Illbackends::Mock');
751     $backend->set_always('name', 'Mock');
752
753     my $config = Test::MockObject->new;
754     $config->set_always('backend_dir', "/tmp");
755
756     my $illrq = $builder->build({source => 'Illrequest'});
757     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
758     $illrq_obj->_config($config);
759     $illrq_obj->_backend($backend);
760
761     $config->set_always('censorship', { censor_notes_staff => 1, censor_reply_date => 0 });
762
763     my $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564 });
764     is_deeply($censor_out, { foo => 'bar', baz => 564, display_reply_date => 1 },
765               "_censor: not OPAC, reply_date = 1");
766
767     $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564, opac => 1 });
768     is_deeply($censor_out, {
769         foo => 'bar', baz => 564, censor_notes_staff => 1,
770         display_reply_date => 1, opac => 1
771     }, "_censor: notes_staff = 0, reply_date = 0");
772
773     $schema->storage->txn_rollback;
774 };
775
776 subtest 'Checking Limits' => sub {
777
778     plan tests => 30;
779
780     $schema->storage->txn_begin;
781
782     # Build infrastructure
783     my $backend = Test::MockObject->new;
784     $backend->set_isa('Koha::Illbackends::Mock');
785     $backend->set_always('name', 'Mock');
786
787     my $config = Test::MockObject->new;
788     $config->set_always('backend_dir', "/tmp");
789
790     my $illrq = $builder->build({source => 'Illrequest'});
791     my $illrq_obj = Koha::Illrequests->find($illrq->{illrequest_id});
792     $illrq_obj->_config($config);
793     $illrq_obj->_backend($backend);
794
795     # getLimits
796     $config->set_series('getLimitRules',
797                         { CPL => { count => 1, method => 'test' } },
798                         { default => { count => 0, method => 'active' } });
799     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
800               { count => 1, method => 'test' },
801               "getLimits: by value.");
802     is_deeply($illrq_obj->getLimits({ type => 'branch' }),
803               { count => 0, method => 'active' },
804               "getLimits: by default.");
805     is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }),
806               { count => -1, method => 'active' },
807               "getLimits: by hard-coded.");
808
809     #_limit_counter
810     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
811        1, "_limit_counter: Initial branch annual count.");
812     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
813        1, "_limit_counter: Initial branch active count.");
814     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
815        1, "_limit_counter: Initial patron annual count.");
816     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
817        1, "_limit_counter: Initial patron active count.");
818     $builder->build({
819         source => 'Illrequest',
820         value => {
821             branchcode => $illrq_obj->branchcode,
822             borrowernumber => $illrq_obj->borrowernumber,
823         }
824     });
825     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
826        2, "_limit_counter: Add a qualifying request for branch annual count.");
827     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
828        2, "_limit_counter: Add a qualifying request for branch active count.");
829     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
830        2, "_limit_counter: Add a qualifying request for patron annual count.");
831     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
832        2, "_limit_counter: Add a qualifying request for patron active count.");
833     $builder->build({
834         source => 'Illrequest',
835         value => {
836             branchcode => $illrq_obj->branchcode,
837             borrowernumber => $illrq_obj->borrowernumber,
838             placed => "2005-05-31",
839         }
840     });
841     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
842        2, "_limit_counter: Add an out-of-date branch request.");
843     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
844        3, "_limit_counter: Add a qualifying request for branch active count.");
845     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
846        2, "_limit_counter: Add an out-of-date patron request.");
847     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
848        3, "_limit_counter: Add a qualifying request for patron active count.");
849     $builder->build({
850         source => 'Illrequest',
851         value => {
852             branchcode => $illrq_obj->branchcode,
853             borrowernumber => $illrq_obj->borrowernumber,
854             status => "COMP",
855         }
856     });
857     is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }),
858        3, "_limit_counter: Add a qualifying request for branch annual count.");
859     is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }),
860        3, "_limit_counter: Add a completed request for branch active count.");
861     is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }),
862        3, "_limit_counter: Add a qualifying request for patron annual count.");
863     is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }),
864        3, "_limit_counter: Add a completed request for patron active count.");
865
866     # check_limits:
867
868     # We've tested _limit_counter, so all we need to test here is whether the
869     # current counts of 3 for each work as they should against different
870     # configuration declarations.
871
872     # No limits
873     $config->set_always('getLimitRules', undef);
874     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
875                                  librarycode => $illrq_obj->branchcode}),
876        1, "check_limits: no configuration => no limits.");
877
878     # Branch tests
879     $config->set_always('getLimitRules',
880                         { $illrq_obj->branchcode => { count => 1, method => 'active' } });
881     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
882                                  librarycode => $illrq_obj->branchcode}),
883        0, "check_limits: branch active limit exceeded.");
884     $config->set_always('getLimitRules',
885                         { $illrq_obj->branchcode => { count => 1, method => 'annual' } });
886     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
887                                  librarycode => $illrq_obj->branchcode}),
888        0, "check_limits: branch annual limit exceeded.");
889     $config->set_always('getLimitRules',
890                         { $illrq_obj->branchcode => { count => 4, method => 'active' } });
891     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
892                                  librarycode => $illrq_obj->branchcode}),
893        1, "check_limits: branch active limit OK.");
894     $config->set_always('getLimitRules',
895                         { $illrq_obj->branchcode => { count => 4, method => 'annual' } });
896     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
897                                  librarycode => $illrq_obj->branchcode}),
898        1, "check_limits: branch annual limit OK.");
899
900     # Patron tests
901     $config->set_always('getLimitRules',
902                         { $illrq_obj->patron->categorycode => { count => 1, method => 'active' } });
903     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
904                                  librarycode => $illrq_obj->branchcode}),
905        0, "check_limits: patron category active limit exceeded.");
906     $config->set_always('getLimitRules',
907                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
908     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
909                                  librarycode => $illrq_obj->branchcode}),
910        0, "check_limits: patron category annual limit exceeded.");
911     $config->set_always('getLimitRules',
912                         { $illrq_obj->patron->categorycode => { count => 4, method => 'active' } });
913     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
914                                  librarycode => $illrq_obj->branchcode}),
915        1, "check_limits: patron category active limit OK.");
916     $config->set_always('getLimitRules',
917                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
918     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
919                                  librarycode => $illrq_obj->branchcode}),
920        1, "check_limits: patron category annual limit OK.");
921
922     # One rule cancels the other
923     $config->set_series('getLimitRules',
924                         # Branch rules allow request
925                         { $illrq_obj->branchcode => { count => 4, method => 'active' } },
926                         # Patron rule forbids it
927                         { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } });
928     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
929                                  librarycode => $illrq_obj->branchcode}),
930        0, "check_limits: patron category veto overrides branch OK.");
931     $config->set_series('getLimitRules',
932                         # Branch rules allow request
933                         { $illrq_obj->branchcode => { count => 1, method => 'active' } },
934                         # Patron rule forbids it
935                         { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } });
936     is($illrq_obj->check_limits({patron => $illrq_obj->patron,
937                                  librarycode => $illrq_obj->branchcode}),
938        0, "check_limits: branch veto overrides patron category OK.");
939
940     $schema->storage->txn_rollback;
941 };
942
943 subtest 'Custom statuses' => sub {
944
945     plan tests => 3;
946
947     $schema->storage->txn_begin;
948
949     my $cat = Koha::AuthorisedValueCategories->search(
950         {
951             category_name => 'ILLSTATUS'
952         }
953     );
954
955     if ($cat->count == 0) {
956         $cat  = $builder->build_object(
957             {
958                 class => 'Koha::AuthorisedValueCategory',
959                 value => {
960                     category_name => 'ILLSTATUS'
961                 }
962             }
963         );
964     };
965
966     my $av = $builder->build_object(
967         {
968             class => 'Koha::AuthorisedValues',
969             value => {
970                 category => 'ILLSTATUS'
971             }
972         }
973     );
974
975     is($av->category, 'ILLSTATUS',
976        "Successfully created authorised value for custom status");
977
978     my $ill_req = $builder->build_object(
979         {
980             class => 'Koha::Illrequests',
981             value => {
982                 status_alias => $av->authorised_value
983             }
984         }
985     );
986     isa_ok($ill_req->statusalias, 'Koha::AuthorisedValue',
987            "statusalias correctly returning Koha::AuthorisedValue object");
988
989     $ill_req->status("COMP");
990     is($ill_req->statusalias, undef,
991         "Koha::Illrequest->status overloading resetting status_alias");
992
993     $schema->storage->txn_rollback;
994 };