Bug 5770: (QA follow-up) Allow feature to be disable
[koha.git] / t / db_dependent / Suggestions.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 DateTime::Duration;
21 use Test::More tests => 107;
22 use Test::Warn;
23
24 use t::lib::Mocks;
25 use t::lib::TestBuilder;
26
27 use C4::Context;
28 use C4::Letters;
29 use C4::Budgets qw( AddBudgetPeriod AddBudget );
30 use Koha::Database;
31 use Koha::DateUtils qw( dt_from_string output_pref );
32 use Koha::Libraries;
33 use Koha::Patrons;
34 use Koha::Suggestions;
35
36 BEGIN {
37     use_ok('C4::Suggestions');
38 }
39
40 my $schema  = Koha::Database->new->schema;
41 $schema->storage->txn_begin;
42 my $dbh = C4::Context->dbh;
43 my $builder = t::lib::TestBuilder->new;
44
45 # Reset item types to only the default ones
46 $dbh->do(q|DELETE FROM itemtypes;|);
47 my $sql = qq|
48 INSERT INTO itemtypes (itemtype, description, rentalcharge, notforloan, imageurl, summary) VALUES
49 ('BK', 'Books',5,0,'bridge/book.gif',''),
50 ('MX', 'Mixed Materials',5,0,'bridge/kit.gif',''),
51 ('CF', 'Computer Files',5,0,'bridge/computer_file.gif',''),
52 ('MP', 'Maps',5,0,'bridge/map.gif',''),
53 ('VM', 'Visual Materials',5,1,'bridge/dvd.gif',''),
54 ('MU', 'Music',5,0,'bridge/sound.gif',''),
55 ('CR', 'Continuing Resources',5,0,'bridge/periodical.gif',''),
56 ('REF', 'Reference',0,1,'bridge/reference.gif','');|;
57 $dbh->do($sql);
58 $dbh->do(q|DELETE FROM suggestions|);
59 $dbh->do(q|DELETE FROM issues|);
60 $dbh->do(q|DELETE FROM borrowers|);
61 $dbh->do(q|DELETE FROM letter|);
62 $dbh->do(q|DELETE FROM message_queue|);
63 $dbh->do(q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'CHECKED', 'my content')|);
64 $dbh->do(q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'NEW_SUGGESTION', 'Content for new suggestion')|);
65
66 # Add CPL if missing.
67 if (not defined Koha::Libraries->find('CPL')) {
68     Koha::Library->new({ branchcode => 'CPL', branchname => 'Centerville' })->store;
69 }
70
71 my $patron_category = $builder->build({ source => 'Category' });
72
73 my $member = {
74     firstname => 'my firstname',
75     surname => 'my surname',
76     categorycode => $patron_category->{categorycode},
77     branchcode => 'CPL',
78     smsalertnumber => 12345,
79 };
80
81 my $member2 = {
82     firstname => 'my firstname',
83     surname => 'my surname',
84     categorycode => $patron_category->{categorycode},
85     branchcode => 'CPL',
86     email => 'to@example.com',
87 };
88
89 my $borrowernumber = Koha::Patron->new($member)->store->borrowernumber;
90 my $borrowernumber2 = Koha::Patron->new($member2)->store->borrowernumber;
91
92 my $biblionumber1 = 1;
93 my $my_suggestion = {
94     title         => 'my title',
95     author        => 'my author',
96     publishercode => 'my publishercode',
97     suggestedby   => $borrowernumber,
98     biblionumber  => $biblionumber1,
99     branchcode    => 'CPL',
100     managedby     => '',
101     manageddate   => '',
102     accepteddate  => dt_from_string,
103     note          => 'my note',
104 };
105
106 my $budgetperiod_id = AddBudgetPeriod({
107     budget_period_startdate   => '2008-01-01',
108     budget_period_enddate     => '2008-12-31',
109     budget_period_description => 'MAPERI',
110     budget_period_active      => 1,
111 });
112
113 my $budget_id = AddBudget({
114     budget_code      => 'ABCD',
115     budget_amount    => '123.132000',
116     budget_name      => 'ABCD',
117     budget_notes     => 'This is a note',
118     budget_period_id => $budgetperiod_id,
119 });
120 my $my_suggestion_with_budget = {
121     title         => 'my title 2',
122     author        => 'my author 2',
123     publishercode => 'my publishercode 2',
124     suggestedby   => $borrowernumber,
125     biblionumber  => $biblionumber1,
126     managedby     => '',
127     manageddate   => '',
128     accepteddate  => dt_from_string,
129     note          => 'my note',
130     budgetid      => $budget_id,
131 };
132 my $my_suggestion_with_budget2 = {
133     title         => 'my title 3',
134     author        => 'my author 3',
135     publishercode => 'my publishercode 3',
136     suggestedby   => $borrowernumber2,
137     biblionumber  => $biblionumber1,
138     managedby     => '',
139     manageddate   => '',
140     accepteddate  => dt_from_string,
141     note          => 'my note',
142     budgetid      => $budget_id,
143 };
144
145 is( CountSuggestion(), 0, 'CountSuggestion without the status returns 0' );
146 is( CountSuggestion('ASKED'), 0, 'CountSuggestion returns the correct number of suggestions' );
147 is( CountSuggestion('CHECKED'), 0, 'CountSuggestion returns the correct number of suggestions' );
148 is( CountSuggestion('ACCEPTED'), 0, 'CountSuggestion returns the correct number of suggestions' );
149 is( CountSuggestion('REJECTED'), 0, 'CountSuggestion returns the correct number of suggestions' );
150
151 my $my_suggestionid = NewSuggestion($my_suggestion);
152 isnt( $my_suggestionid, 0, 'NewSuggestion returns an not null id' );
153 my $my_suggestionid_with_budget = NewSuggestion($my_suggestion_with_budget);
154
155 is( GetSuggestion(), undef, 'GetSuggestion without the suggestion id returns undef' );
156 my $suggestion = GetSuggestion($my_suggestionid);
157 is( $suggestion->{title}, $my_suggestion->{title}, 'NewSuggestion stores the title correctly' );
158 is( $suggestion->{author}, $my_suggestion->{author}, 'NewSuggestion stores the author correctly' );
159 is( $suggestion->{publishercode}, $my_suggestion->{publishercode}, 'NewSuggestion stores the publishercode correctly' );
160 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'NewSuggestion stores the borrower number correctly' );
161 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'NewSuggestion stores the biblio number correctly' );
162 is( $suggestion->{STATUS}, 'ASKED', 'NewSuggestion stores a suggestion with the status ASKED by default' );
163 is( $suggestion->{managedby}, undef, 'NewSuggestion stores empty string as undef for non existent foreign key (integer)' );
164 is( $suggestion->{manageddate}, undef, 'NewSuggestion stores empty string as undef for date' );
165 is( $suggestion->{budgetid}, undef, 'NewSuggestion should set budgetid to NULL if not given' );
166
167 is( CountSuggestion('ASKED'), 2, 'CountSuggestion returns the correct number of suggestions' );
168
169
170 is( ModSuggestion(), undef, 'ModSuggestion without the suggestion returns undef' );
171 my $mod_suggestion1 = {
172     title         => 'my modified title',
173     author        => 'my modified author',
174     publishercode => 'my modified publishercode',
175     managedby     => '',
176     manageddate   => '',
177 };
178 my $status = ModSuggestion($mod_suggestion1);
179 is( $status, undef, 'ModSuggestion without the suggestion id returns undef' );
180
181 $mod_suggestion1->{suggestionid} = $my_suggestionid;
182 $status = ModSuggestion($mod_suggestion1);
183 is( $status, 1, 'ModSuggestion modifies one entry' );
184 $suggestion = GetSuggestion($my_suggestionid);
185 is( $suggestion->{title}, $mod_suggestion1->{title}, 'ModSuggestion modifies the title  correctly' );
186 is( $suggestion->{author}, $mod_suggestion1->{author}, 'ModSuggestion modifies the author correctly' );
187 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'ModSuggestion modifies the publishercode correctly' );
188 is( $suggestion->{managedby}, undef, 'ModSuggestion stores empty string as undef for non existent foreign key (integer)' );
189 is( $suggestion->{manageddate}, undef, 'ModSuggestion stores empty string as undef for date' );
190 isnt( $suggestion->{accepteddate}, undef, 'ModSuggestion does not update a non given date value' );
191 is( $suggestion->{note}, 'my note', 'ModSuggestion should not erase data if not given' );
192
193 my $messages = C4::Letters::GetQueuedMessages({
194     borrowernumber => $borrowernumber,
195     letter_code => 'CHECKED',
196 });
197 is( @$messages, 0, 'ModSuggestions does not send an email if the status is not updated' );
198
199 my $mod_suggestion2 = {
200     STATUS       => 'STALLED',
201     suggestionid => $my_suggestionid,
202 };
203 warning_is { $status = ModSuggestion($mod_suggestion2) }
204            "No suggestions STALLED letter transported by email",
205            "ModSuggestion status warning is correct";
206 is( $status, 1, "ModSuggestion Status OK");
207
208 my $mod_suggestion3 = {
209     STATUS       => 'CHECKED',
210     suggestionid => $my_suggestionid,
211 };
212
213 #Test the message_transport_type of suggestion notices
214
215 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is disabled
216 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 0 );
217 $status = ModSuggestion($mod_suggestion3);
218 is( $status, 1, 'ModSuggestion modifies one entry' );
219 $suggestion = GetSuggestion($my_suggestionid);
220 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'ModSuggestion modifies the status correctly' );
221 $messages = C4::Letters::GetQueuedMessages({
222     borrowernumber => $borrowernumber,
223     letter_code => 'CHECKED',
224 });
225 is( @$messages, 1, 'ModSuggestion sends an email if the status is updated' );
226 is ($messages->[0]->{message_transport_type}, 'email', 'When FallbackToSMSIfNoEmail syspref is disabled the suggestion message_transport_type is always email');
227 is( CountSuggestion('CHECKED'), 1, 'CountSuggestion returns the correct number of suggestions' );
228
229 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a smsalertnumber and no email
230 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 );
231 ModSuggestion($mod_suggestion3);
232 $messages = C4::Letters::GetQueuedMessages({
233     borrowernumber => $borrowernumber,
234     letter_code => 'CHECKED',
235 });
236 is ($messages->[1]->{message_transport_type}, 'sms', 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is sms if the borrower has no email');
237
238 #Make a new suggestion for a borrower with defined email and no smsalertnumber
239 my $my_suggestion_2_id = NewSuggestion($my_suggestion_with_budget2);
240
241 #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a defined email and no smsalertnumber
242 t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 );
243 my $mod_suggestion4 = {
244     STATUS       => 'CHECKED',
245     suggestionid => $my_suggestion_2_id,
246 };
247 ModSuggestion($mod_suggestion4);
248 $messages = C4::Letters::GetQueuedMessages({
249     borrowernumber => $borrowernumber2,
250     letter_code => 'CHECKED',
251 });
252 is ($messages->[0]->{message_transport_type}, 'email', 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is email if the borrower has an email');
253
254 is( GetSuggestionInfo(), undef, 'GetSuggestionInfo without the suggestion id returns undef' );
255 $suggestion = GetSuggestionInfo($my_suggestionid);
256 is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfo returns the suggestion id correctly' );
257 is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfo returns the title correctly' );
258 is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfo returns the author correctly' );
259 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfo returns the publisher code correctly' );
260 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' );
261 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfo returns the biblio number correctly' );
262 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfo returns the status correctly' );
263 is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfo returns the surname correctly' );
264 is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfo returns the firstname correctly' );
265 is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' );
266
267
268 is( GetSuggestionFromBiblionumber(), undef, 'GetSuggestionFromBiblionumber without the biblio number returns undef' );
269 is( GetSuggestionFromBiblionumber(2), undef, 'GetSuggestionFromBiblionumber with an invalid biblio number returns undef' );
270 is( GetSuggestionFromBiblionumber($biblionumber1), $my_suggestionid, 'GetSuggestionFromBiblionumber functions correctly' );
271
272
273 is( GetSuggestionInfoFromBiblionumber(), undef, 'GetSuggestionInfoFromBiblionumber without the biblio number returns undef' );
274 is( GetSuggestionInfoFromBiblionumber(2), undef, 'GetSuggestionInfoFromBiblionumber with an invalid biblio number returns undef' );
275 $suggestion = GetSuggestionInfoFromBiblionumber($biblionumber1);
276 is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfoFromBiblionumber returns the suggestion id correctly' );
277 is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfoFromBiblionumber returns the title correctly' );
278 is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfoFromBiblionumber returns the author correctly' );
279 is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfoFromBiblionumber returns the publisher code correctly' );
280 is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumber returns the borrower number correctly' );
281 is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfoFromBiblionumber returns the biblio number correctly' );
282 is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfoFromBiblionumber returns the status correctly' );
283 is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfoFromBiblionumber returns the surname correctly' );
284 is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfoFromBiblionumber returns the firstname correctly' );
285 is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumeber returns the borrower number correctly' );
286
287
288 my $suggestions = GetSuggestionByStatus();
289 is( @$suggestions, 0, 'GetSuggestionByStatus without the status returns an empty array' );
290 $suggestions = GetSuggestionByStatus('CHECKED');
291 is( @$suggestions, 2, 'GetSuggestionByStatus returns the correct number of suggestions' );
292 is( $suggestions->[0]->{suggestionid}, $my_suggestionid, 'GetSuggestionByStatus returns the suggestion id correctly' );
293 is( $suggestions->[0]->{title}, $mod_suggestion1->{title}, 'GetSuggestionByStatus returns the title correctly' );
294 is( $suggestions->[0]->{author}, $mod_suggestion1->{author}, 'GetSuggestionByStatus returns the author correctly' );
295 is( $suggestions->[0]->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionByStatus returns the publisher code correctly' );
296 is( $suggestions->[0]->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' );
297 is( $suggestions->[0]->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionByStatus returns the biblio number correctly' );
298 is( $suggestions->[0]->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionByStatus returns the status correctly' );
299 is( $suggestions->[0]->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionByStatus returns the surname correctly' );
300 is( $suggestions->[0]->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionByStatus returns the firstname correctly' );
301 is( $suggestions->[0]->{branchcodesuggestedby}, $member->{branchcode}, 'GetSuggestionByStatus returns the branch code correctly' );
302 is( $suggestions->[0]->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' );
303 is( $suggestions->[0]->{categorycodesuggestedby}, $member->{categorycode}, 'GetSuggestionByStatus returns the category code correctly' );
304
305
306 is( ConnectSuggestionAndBiblio(), '0E0', 'ConnectSuggestionAndBiblio without arguments returns 0E0' );
307 my $biblionumber2 = 2;
308 my $connect_suggestion_and_biblio = ConnectSuggestionAndBiblio($my_suggestionid, $biblionumber2);
309 is( $connect_suggestion_and_biblio, '1', 'ConnectSuggestionAndBiblio returns 1' );
310 $suggestion = GetSuggestion($my_suggestionid);
311 is( $suggestion->{biblionumber}, $biblionumber2, 'ConnectSuggestionAndBiblio updates the biblio number correctly' );
312
313 my $search_suggestion = SearchSuggestion();
314 is( @$search_suggestion, 3, 'SearchSuggestion without arguments returns all suggestions' );
315
316 $search_suggestion = SearchSuggestion({
317     title => $mod_suggestion1->{title},
318 });
319 is( @$search_suggestion, 1, 'SearchSuggestion returns the correct number of suggestions' );
320 $search_suggestion = SearchSuggestion({
321     title => 'another title',
322 });
323 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
324
325 $search_suggestion = SearchSuggestion({
326     author => $mod_suggestion1->{author},
327 });
328 is( @$search_suggestion, 1, 'SearchSuggestion returns the correct number of suggestions' );
329 $search_suggestion = SearchSuggestion({
330     author => 'another author',
331 });
332 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
333
334 $search_suggestion = SearchSuggestion({
335     publishercode => $mod_suggestion1->{publishercode},
336 });
337 is( @$search_suggestion, 1, 'SearchSuggestion returns the correct number of suggestions' );
338 $search_suggestion = SearchSuggestion({
339     publishercode => 'another publishercode',
340 });
341 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
342
343 $search_suggestion = SearchSuggestion({
344     STATUS => $mod_suggestion3->{STATUS},
345 });
346 is( @$search_suggestion, 2, 'SearchSuggestion returns the correct number of suggestions' );
347
348 $search_suggestion = SearchSuggestion({
349     STATUS => q||
350 });
351 is( @$search_suggestion, 0, 'SearchSuggestion should not return all suggestions if we want the suggestions with a STATUS=""' );
352 $search_suggestion = SearchSuggestion({
353     STATUS => 'REJECTED',
354 });
355 is( @$search_suggestion, 0, 'SearchSuggestion returns the correct number of suggestions' );
356
357 $search_suggestion = SearchSuggestion({
358     budgetid => '',
359 });
360 is( @$search_suggestion, 3, 'SearchSuggestion (budgetid = "") returns the correct number of suggestions' );
361 $search_suggestion = SearchSuggestion({
362     budgetid => $budget_id,
363 });
364 is( @$search_suggestion, 2, 'SearchSuggestion (budgetid = $budgetid) returns the correct number of suggestions' );
365 $search_suggestion = SearchSuggestion({
366     budgetid => '__NONE__',
367 });
368 is( @$search_suggestion, 1, 'SearchSuggestion (budgetid = "__NONE__") returns the correct number of suggestions' );
369 $search_suggestion = SearchSuggestion({
370     budgetid => '__ANY__',
371 });
372 is( @$search_suggestion, 3, 'SearchSuggestion (budgetid = "__ANY__") returns the correct number of suggestions' );
373
374 my $del_suggestion = {
375     title => 'my deleted title',
376     STATUS => 'CHECKED',
377     suggestedby => $borrowernumber,
378 };
379 my $del_suggestionid = NewSuggestion($del_suggestion);
380
381 is( CountSuggestion('CHECKED'), 3, 'CountSuggestion returns the correct number of suggestions' );
382
383 is( DelSuggestion(), '0E0', 'DelSuggestion without arguments returns 0E0' );
384 is( DelSuggestion($borrowernumber), '', 'DelSuggestion without the suggestion id returns an empty string' );
385 is( DelSuggestion(undef, $my_suggestionid), '', 'DelSuggestion with an invalid borrower number returns an empty string' );
386 $suggestion = DelSuggestion($borrowernumber, $my_suggestionid);
387 is( $suggestion, 1, 'DelSuggestion deletes one suggestion' );
388
389 $suggestions = GetSuggestionByStatus('CHECKED');
390 is( @$suggestions, 2, 'DelSuggestion deletes one suggestion' );
391 is( $suggestions->[1]->{title}, $del_suggestion->{title}, 'DelSuggestion deletes the correct suggestion' );
392
393 # Test budgetid fk
394 $my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB
395 my $my_suggestionid_test_budgetid = NewSuggestion($my_suggestion);
396 $suggestion = GetSuggestion($my_suggestionid_test_budgetid);
397 is( $suggestion->{budgetid}, undef, 'NewSuggestion Should set budgetid to NULL if equals an empty string' );
398
399 $my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB
400 ModSuggestion( $my_suggestion );
401 $suggestion = GetSuggestion($my_suggestionid_test_budgetid);
402 is( $suggestion->{budgetid}, undef, 'NewSuggestion Should set budgetid to NULL if equals an empty string' );
403
404 subtest 'GetUnprocessedSuggestions' => sub {
405     plan tests => 11;
406     $dbh->do(q|DELETE FROM suggestions|);
407     my $my_suggestionid         = NewSuggestion($my_suggestion);
408     my $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
409     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return 0 if a suggestion has been processed but not linked to a fund' );
410     my $status     = ModSuggestion($mod_suggestion1);
411     my $suggestion = GetSuggestion($my_suggestionid);
412     is( $suggestion->{budgetid}, undef, 'ModSuggestion should set budgetid to NULL if not given' );
413     ModSuggestion( { suggestionid => $my_suggestionid, budgetid => $budget_id } );
414     $suggestion = GetSuggestion($my_suggestionid);
415     is( $suggestion->{budgetid}, $budget_id, 'ModSuggestion should modify budgetid if given' );
416
417     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
418     is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' );
419
420     warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'REJECTED' } ) }
421                 'No suggestions REJECTED letter transported by email',
422                 'Warning raised if no REJECTED letter by email';
423     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
424     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' );
425
426     warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'ASKED', suggesteddate => dt_from_string->add_duration( DateTime::Duration->new( days => -4 ) ) } ); }
427                 'No suggestions ASKED letter transported by email',
428                 'Warning raised if no ASKED letter by email';
429     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions;
430     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should use 0 as default value for days' );
431     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(4);
432     is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion suggested 4 days ago' );
433     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(3);
434     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 3 days ago' );
435     $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(5);
436     is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 5 days ago' );
437 };
438
439 subtest 'DelSuggestionsOlderThan' => sub {
440     plan tests => 6;
441
442     Koha::Suggestions->delete;
443
444     # Add four suggestions; note that STATUS needs uppercase (FIXME)
445     my $d1 = output_pref({ dt => dt_from_string->add(days => -2), dateformat => 'sql' });
446     my $d2 = output_pref({ dt => dt_from_string->add(days => -4), dateformat => 'sql' });
447     my $sugg01 = $builder->build({ source => 'Suggestion', value => { date => $d1, STATUS => 'ASKED' }});
448     my $sugg02 = $builder->build({ source => 'Suggestion', value => { date => $d1, STATUS => 'CHECKED' }});
449     my $sugg03 = $builder->build({ source => 'Suggestion', value => { date => $d2, STATUS => 'ASKED' }});
450     my $sugg04 = $builder->build({ source => 'Suggestion', value => { date => $d2, STATUS => 'ACCEPTED' }});
451
452     # Test no parameter: should do nothing
453     C4::Suggestions::DelSuggestionsOlderThan();
454     is( Koha::Suggestions->count, 4, 'No suggestions deleted' );
455     # Test zero: should do nothing too
456     C4::Suggestions::DelSuggestionsOlderThan(0);
457     is( Koha::Suggestions->count, 4, 'No suggestions deleted again' );
458     # Test negative value
459     C4::Suggestions::DelSuggestionsOlderThan(-1);
460     is( Koha::Suggestions->count, 4, 'No suggestions deleted for -1' );
461
462     # Test positive values
463     C4::Suggestions::DelSuggestionsOlderThan(5);
464     is( Koha::Suggestions->count, 4, 'No suggestions>5d deleted' );
465     C4::Suggestions::DelSuggestionsOlderThan(3);
466     is( Koha::Suggestions->count, 3, '1 suggestions>3d deleted' );
467     C4::Suggestions::DelSuggestionsOlderThan(1);
468     is( Koha::Suggestions->count, 2, '1 suggestions>1d deleted' );
469 };
470
471 subtest 'EmailPurchaseSuggestions' => sub {
472     plan tests => 6;
473
474     $dbh->do(q|DELETE FROM message_queue|);
475
476     Koha::Libraries->find('CPL')->update({ branchemail => 'branchemail@b.c' });
477     t::lib::Mocks::mock_preference( "KohaAdminEmailAddress", 'root@localhost');
478     t::lib::Mocks::mock_preference( "EmailAddressForSuggestions", 'a@b.c');
479
480     # EmailAddressForSuggestions or BranchEmailAddress or KohaAdminEmailAddress or 0
481     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "0");
482     NewSuggestion($my_suggestion);
483     my $newsuggestions_messages = C4::Letters::GetQueuedMessages({
484             borrowernumber => $borrowernumber
485         });
486
487     is( @$newsuggestions_messages, 0, 'NewSuggestions does not send an email when disabled' );
488
489     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "KohaAdminEmailAddress");
490     NewSuggestion($my_suggestion);
491     my $newsuggestions_messages = C4::Letters::GetQueuedMessages({
492             borrowernumber => $borrowernumber,
493             letter_code => 'NEW_SUGGESTION',
494         });
495
496     is( @$newsuggestions_messages, 1, 'NewSuggestions sends an email' );
497     my $message1 = C4::Letters::GetMessage( $newsuggestions_messages->[0]->{message_id});
498     is ($message1->{to_address}, 'root@localhost', 'to_address is KohaAdminEmailAddress');
499
500     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "EmailAddressForSuggestions");
501     NewSuggestion($my_suggestion);
502     $newsuggestions_messages = C4::Letters::GetQueuedMessages({
503             borrowernumber => $borrowernumber,
504             letter_code => 'NEW_SUGGESTION',
505         });
506     my $message2 = C4::Letters::GetMessage( $newsuggestions_messages->[1]->{message_id});
507     is ($message2->{to_address}, 'a@b.c', 'to_address is EmailAddressForSuggestions');
508
509     t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "BranchEmailAddress");
510     NewSuggestion($my_suggestion);
511     $newsuggestions_messages = C4::Letters::GetQueuedMessages({
512             borrowernumber => $borrowernumber,
513             letter_code => 'NEW_SUGGESTION',
514         });
515     my $message3 = C4::Letters::GetMessage( $newsuggestions_messages->[2]->{message_id});
516     is ($message3->{to_address}, 'branchemail@b.c', 'to_address is BranchEmailAddress');
517
518     Koha::Libraries->find('CPL')->update({ branchemail => undef });
519     NewSuggestion($my_suggestion);
520     $newsuggestions_messages = C4::Letters::GetQueuedMessages({
521             borrowernumber => $borrowernumber,
522             letter_code => 'NEW_SUGGESTION',
523         });
524     my $message4 = C4::Letters::GetMessage( $newsuggestions_messages->[3]->{message_id});
525     isnt ($message4->{to_address}, 'branchemail@b.c', 'to_address is KohaAdminEmailAddress. Because branchemail is undef');
526
527 };
528
529 $schema->storage->txn_rollback;