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