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