Bug 36122: Update unit test
[koha.git] / t / db_dependent / Koha / Suggestions.t
1 #!/usr/bin/perl
2
3 # Copyright 2015-2019 Koha Development team
4 #
5 # This file is part of Koha
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Test::More tests => 11;
23 use Test::Exception;
24
25 use Koha::Suggestions;
26 use Koha::Notice::Messages;
27 use Koha::Database;
28 use Koha::DateUtils qw( dt_from_string output_pref );
29
30 use t::lib::Mocks;
31 use t::lib::TestBuilder;
32
33 my $schema = Koha::Database->new->schema;
34 $schema->storage->txn_begin;
35
36 my $builder           = t::lib::TestBuilder->new;
37 my $biblio_1          = $builder->build_sample_biblio;
38 my $biblio_2          = $builder->build_sample_biblio;
39 my $patron            = $builder->build( { source => 'Borrower' } );
40 my $nb_of_suggestions = Koha::Suggestions->search->count;
41 my $new_suggestion_1  = Koha::Suggestion->new(
42     {   suggestedby  => $patron->{borrowernumber},
43         biblionumber => $biblio_1->biblionumber,
44     }
45 )->store;
46 my $new_suggestion_2 = Koha::Suggestion->new(
47     {   suggestedby  => $patron->{borrowernumber},
48         biblionumber => $biblio_2->biblionumber,
49     }
50 )->store;
51
52 subtest 'store' => sub {
53     plan tests => 8;
54     my $suggestion  = Koha::Suggestion->new(
55         {   suggestedby  => $patron->{borrowernumber},
56             biblionumber => $biblio_1->biblionumber,
57         }
58     )->store;
59
60     is( $suggestion->suggesteddate, dt_from_string()->ymd, "If suggesteddate not passed in, it will default to today" );
61     my $two_days_ago = dt_from_string->subtract( days => 2 );
62     my $two_days_ago_sql = output_pref({dt => $two_days_ago, dateformat => 'sql', dateonly => 1 });
63     $suggestion->suggesteddate($two_days_ago)->store;
64     $suggestion = Koha::Suggestions->find( $suggestion->suggestionid );
65     is( $suggestion->suggesteddate, $two_days_ago_sql, 'If suggesteddate passed in, it should be taken into account' );
66     $suggestion->reason('because!')->store;
67     $suggestion = Koha::Suggestions->find( $suggestion->suggestionid );
68     is( $suggestion->suggesteddate, $two_days_ago_sql, 'If suggestion id modified, suggesteddate should not be modified' );
69
70     t::lib::Mocks::mock_preference( 'EmailPurchaseSuggestions', 0 );
71     Koha::Notice::Messages->search->delete;
72     $suggestion->STATUS('ASKED')->store;
73     my $last_message = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->single;
74     if ( !defined $last_message ) {
75         $last_message = "No message was sent";
76     }
77     is(
78         $last_message, 'No message was sent',
79         'If EmailPurchaseSuggestions is not enabled, a message should not be sent'
80     );
81
82     t::lib::Mocks::mock_preference( 'EmailPurchaseSuggestions', 'EmailAddressForSuggestions' );
83     Koha::Notice::Messages->search->delete;
84     $suggestion->STATUS('ASKED')->store;
85     $last_message = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->single;
86     if ( !defined $last_message ) {
87         fail('No message was sent');
88     } else {
89         is(
90             $last_message->letter_code, 'NEW_SUGGESTION',
91             'If EmailPurchaseSuggestions is enabled and the status of suggestion is set to ASKED, a message should be sent'
92         );
93     }
94
95     Koha::Notice::Messages->search->delete;
96     $suggestion->STATUS('ACCEPTED')->store;
97     $last_message = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->single;
98     if ( !defined $last_message ) {
99         $last_message = "No message was sent";
100     }
101     is(
102         $last_message, 'No message was sent',
103         'If the status of suggestion is not set to ASKED, a message should not be sent'
104     );
105
106     throws_ok {
107         $suggestion->STATUS('UNKNOWN')->store;
108     }
109     'Koha::Exceptions::Suggestion::StatusForbidden',
110         'store raises an exception on invalid STATUS';
111
112     my $authorised_value = Koha::AuthorisedValue->new(
113         {
114             category         => 'SUGGEST_STATUS',
115             authorised_value => 'UNKNOWN'
116         }
117     )->store;
118     $suggestion->STATUS('UNKNOWN')->store;
119     is( $suggestion->STATUS, 'UNKNOWN', "UNKNOWN status stored" );
120     $suggestion->delete;
121 };
122
123 like( $new_suggestion_1->suggestionid, qr|^\d+$|, 'Adding a new suggestion should have set the suggestionid' );
124 is( Koha::Suggestions->search->count, $nb_of_suggestions + 2, 'The 2 suggestions should have been added' );
125
126 my $retrieved_suggestion_1 = Koha::Suggestions->find( $new_suggestion_1->suggestionid );
127 is( $retrieved_suggestion_1->biblionumber, $new_suggestion_1->biblionumber, 'Find a suggestion by id should return the correct suggestion' );
128
129 $retrieved_suggestion_1->delete;
130 is( Koha::Suggestions->search->count, $nb_of_suggestions + 1, 'Delete should have deleted the suggestion' );
131
132 $schema->storage->txn_rollback;
133
134 subtest 'constraints' => sub {
135     plan tests => 11;
136     $schema->storage->txn_begin;
137
138     my $print_error = $schema->storage->dbh->{PrintError};
139     $schema->storage->dbh->{PrintError} = 0;
140
141     my $patron = $builder->build_object( { class => "Koha::Patrons" } );
142     my $biblio = $builder->build_sample_biblio();
143     my $branch = $builder->build_object( { class => "Koha::Libraries" } );
144
145     my $suggestion = $builder->build_object(
146         {
147             class => "Koha::Suggestions",
148             value => {
149                 suggestedby  => $patron->borrowernumber,
150                 biblionumber => $biblio->biblionumber,
151                 branchcode   => $branch->branchcode,
152                 managedby    => undef,
153                 acceptedby   => undef,
154                 rejectedby   => undef,
155                 budgetid     => undef,
156             }
157         }
158     );
159
160     my $nonexistent_borrowernumber = $patron->borrowernumber;
161     # suggestedby
162     $patron->delete;
163     $suggestion = $suggestion->get_from_storage;
164     is( $suggestion->suggestedby, undef,
165         "The suggestion is not deleted when the related patron is deleted" );
166
167     # biblionumber
168     $biblio->delete;
169     $suggestion = $suggestion->get_from_storage;
170     is( $suggestion->biblionumber, undef,
171         "The suggestion is not deleted when the related biblio is deleted" );
172
173     # branchcode
174     $branch->delete;
175     $suggestion = $suggestion->get_from_storage;
176     is( $suggestion->branchcode, undef,
177         "The suggestion is not deleted when the related branch is deleted" );
178
179     # managerid
180     {   # hide useless warnings
181         local *STDERR;
182         open STDERR, '>', '/dev/null';
183         throws_ok {
184             $suggestion->managedby($nonexistent_borrowernumber)->store;
185         }
186         'Koha::Exceptions::Object::FKConstraint',
187           'store raises an exception on invalid managerid';
188         close STDERR;
189     }
190     my $manager = $builder->build_object( { class => "Koha::Patrons" } );
191     $suggestion->managedby( $manager->borrowernumber )->store;
192     $manager->delete;
193     $suggestion = $suggestion->get_from_storage;
194     is( $suggestion->managedby, undef,
195         "The suggestion is not deleted when the related manager is deleted" );
196
197     # acceptedby
198     {    # hide useless warnings
199         local *STDERR;
200         open STDERR, '>', '/dev/null';
201         throws_ok {
202             $suggestion->acceptedby($nonexistent_borrowernumber)->store;
203         }
204         'Koha::Exceptions::Object::FKConstraint',
205           'store raises an exception on invalid acceptedby id';
206         close STDERR;
207     }
208     my $acceptor = $builder->build_object( { class => "Koha::Patrons" } );
209     $suggestion->acceptedby( $acceptor->borrowernumber )->store;
210     $acceptor->delete;
211     $suggestion = $suggestion->get_from_storage;
212     is( $suggestion->acceptedby, undef,
213         "The suggestion is not deleted when the related acceptor is deleted" );
214
215     # rejectedby
216     {    # hide useless warnings
217         local *STDERR;
218         open STDERR, '>', '/dev/null';
219         throws_ok {
220             $suggestion->rejectedby($nonexistent_borrowernumber)->store;
221         }
222         'Koha::Exceptions::Object::FKConstraint',
223           'store raises an exception on invalid rejectedby id';
224         close STDERR;
225     }
226     my $rejecter = $builder->build_object( { class => "Koha::Patrons" } );
227     $suggestion->rejectedby( $rejecter->borrowernumber )->store;
228     $rejecter->delete;
229     $suggestion = $suggestion->get_from_storage;
230     is( $suggestion->rejectedby, undef,
231         "The suggestion is not deleted when the related rejecter is deleted" );
232
233     # budgetid
234     {    # hide useless warnings
235         local *STDERR;
236         open STDERR, '>', '/dev/null';
237
238         throws_ok { $suggestion->budgetid($nonexistent_borrowernumber)->store; }
239         'Koha::Exceptions::Object::FKConstraint',
240           'store raises an exception on invalid budgetid';
241         close STDERR;
242     }
243     my $fund = $builder->build_object( { class => "Koha::Acquisition::Funds" } );
244     $suggestion->budgetid( $fund->id )->store;
245     $fund->delete;
246     $suggestion = $suggestion->get_from_storage;
247     is( $suggestion->budgetid, undef,
248         "The suggestion is not deleted when the related budget is deleted" );
249
250     $schema->storage->dbh->{PrintError} = $print_error;
251     $schema->storage->txn_rollback;
252 };
253
254 subtest 'manager, suggester, rejecter, last_modifier' => sub {
255     plan tests => 8;
256     $schema->storage->txn_begin;
257
258     my $suggestion = $builder->build_object( { class => 'Koha::Suggestions' } );
259
260     is( ref( $suggestion->manager ),
261         'Koha::Patron',
262         '->manager should have returned a Koha::Patron object' );
263     is( ref( $suggestion->rejecter ),
264         'Koha::Patron',
265         '->rejecter should have returned a Koha::Patron object' );
266     is( ref( $suggestion->suggester ),
267         'Koha::Patron',
268         '->suggester should have returned a Koha::Patron object' );
269     is( ref( $suggestion->last_modifier ),
270         'Koha::Patron',
271         '->last_modifier should have returned a Koha::Patron object' );
272
273     $suggestion->set(
274         {
275             managedby          => undef,
276             rejectedby         => undef,
277             suggestedby        => undef,
278             lastmodificationby => undef
279         }
280     );
281
282     is( $suggestion->manager, undef,
283         '->manager should have returned undef if no manager set' );
284     is( $suggestion->rejecter, undef,
285         '->rejecter should have returned undef if no rejecter set' );
286     is( $suggestion->suggester, undef,
287         '->suggester should have returned undef if no suggester set' );
288     is( $suggestion->last_modifier,
289         undef,
290         '->last_modifier should have returned undef if no last_modifier set' );
291
292     $schema->storage->txn_rollback;
293 };
294
295 subtest 'fund' => sub {
296     plan tests => 2;
297
298     $schema->storage->txn_begin;
299
300     my $suggestion = $builder->build_object( { class => 'Koha::Suggestions' } );
301     is( ref( $suggestion->fund ),
302         'Koha::Acquisition::Fund',
303         '->fund should have returned a Koha::Acquisition::Fund object' );
304
305     $suggestion->set( { budgetid => undef } );
306
307     is( $suggestion->fund, undef,
308         '->fund should have returned undef if not fund set' );
309
310     $schema->storage->txn_rollback;
311 };
312
313 subtest 'search_limited() tests' => sub {
314
315     plan tests => 4;
316
317     $schema->storage->txn_begin;
318
319     # Two libraries
320     my $library_1 = $builder->build_object({ class => 'Koha::Libraries' });
321     my $library_2 = $builder->build_object({ class => 'Koha::Libraries' });
322
323     # A patron from $library_1, that is not superlibrarian at all
324     my $patron = $builder->build_object(
325         {
326             class => 'Koha::Patrons',
327             value => { branchcode => $library_1->id, flags => 0 }
328         }
329     );
330
331     # Add 3 suggestions, to be sorted by author
332     my $suggestion_1 = $builder->build_object(
333         {
334             class => 'Koha::Suggestions',
335             value => { branchcode => $library_1->id, author => 'A' }
336         }
337     );
338     my $suggestion_2 = $builder->build_object(
339         {
340             class => 'Koha::Suggestions',
341             value => { branchcode => $library_2->id, author => 'B' }
342         }
343     );
344     my $suggestion_3 = $builder->build_object(
345         {
346             class => 'Koha::Suggestions',
347             value => { branchcode => $library_2->id, author => 'C' }
348         }
349     );
350
351     my $resultset = Koha::Suggestions->search(
352         { branchcode => [ $library_1->id, $library_2->id ] },
353         { order_by   => { -desc => ['author'] } } );
354
355     is( $resultset->count, 3, 'Only this three suggestions are returned' );
356
357     # Now the tests
358     t::lib::Mocks::mock_userenv({ patron => $patron, branchcode => $library_1->id });
359
360     # Disable IndependentBranches
361     t::lib::Mocks::mock_preference( 'IndependentBranches', 0 );
362
363     my $filtered_rs = $resultset->search_limited;
364     is( $filtered_rs->count, 3, 'No IndependentBranches, all suggestions returned' );
365
366     # Enable IndependentBranches
367     t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
368
369     $filtered_rs = $resultset->search_limited;
370
371     is( $filtered_rs->count, 1, 'IndependentBranches, only suggestions from own branch returned' );
372
373     # Make the patron superlibrarian to override IndependentBranches
374     $patron->flags(1)->store;
375     # So it reloads C4::Context->userenv->{flags}
376     t::lib::Mocks::mock_userenv({ patron => $patron, branchcode => $library_1->id });
377
378     $filtered_rs = $resultset->search_limited;
379     is( $filtered_rs->count, 3, 'IndependentBranches but patron is superlibrarian, all suggestions returned' );
380
381     $schema->storage->txn_rollback;
382 };
383
384 subtest 'filter_by_pending() tests' => sub {
385
386     plan tests => 3;
387
388     $schema->storage->txn_begin;
389
390     my $suggestion_1 = $builder->build_object( { class => 'Koha::Suggestions', value => { STATUS => 'ASKED' } } );
391     my $suggestion_2 = $builder->build_object( { class => 'Koha::Suggestions', value => { STATUS => 'ACCEPTED' } } );
392     my $suggestion_3 = $builder->build_object( { class => 'Koha::Suggestions', value => { STATUS => 'ASKED' } } );
393
394     my $suggestions =
395       Koha::Suggestions->search( { suggestionid => [ $suggestion_1->id, $suggestion_2->id, $suggestion_3->id ] },
396         { order_by => ['suggestionid'] } );
397
398     is( $suggestions->count, 3 );
399
400     my $pending     = $suggestions->filter_by_pending;
401     my @pending_ids = $pending->get_column('suggestionid');
402
403     is( $pending->count, 2 );
404     is_deeply( \@pending_ids, [ $suggestion_1->id, $suggestion_3->id ] );
405
406     $schema->storage->txn_rollback;
407 };
408
409 subtest 'filter_by_suggested_days_range() tests' => sub {
410
411     plan tests => 4;
412
413     $schema->storage->txn_begin;
414
415     my $today             = dt_from_string;
416     my $today_minus_two   = dt_from_string->subtract( days => 2 );
417     my $today_minus_three = dt_from_string->subtract( days => 3 );
418
419     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
420
421     my $suggestion_1 = $builder->build_object(
422         { class => 'Koha::Suggestions', value => { suggesteddate => $dtf->format_date($today) } } );
423     my $suggestion_2 = $builder->build_object(
424         { class => 'Koha::Suggestions', value => { suggesteddate => $dtf->format_date($today_minus_two) } } );
425     my $suggestion_3 = $builder->build_object(
426         { class => 'Koha::Suggestions', value => { suggesteddate => $dtf->format_date($today_minus_three) } } );
427
428     my $suggestions =
429       Koha::Suggestions->search( { suggestionid => [ $suggestion_1->id, $suggestion_2->id, $suggestion_3->id ] },
430         { order_by => ['suggestionid'] } );
431
432     is( $suggestions->count, 3 );
433
434     my $three_days = $suggestions->filter_by_suggested_days_range(3);
435     is( $three_days->count, 3 );
436
437     my $two_days = $suggestions->filter_by_suggested_days_range(2);
438     is( $two_days->count, 2 );
439
440     my $one_days = $suggestions->filter_by_suggested_days_range(1);
441     is( $one_days->count, 1 );
442
443     $schema->storage->txn_rollback;
444 };