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