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